#! /usr/local/bin/perl
#!/usr/bin/env perl
# -*- perl -*-

#
# $Id: bbbikeclient,v 1.12 2007/06/10 19:08:29 eserte Exp $
# Author: Slaven Rezic
#
# Copyright (C) 1999,2001,2005,2007 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: eserte@users.sourceforge.net
# WWW:  http://bbbike.sourceforge.net
#

use FindBin;
use lib "$FindBin::RealBin";
use BBBikeServer;
use Getopt::Long;
use strict;
use vars qw($VERBOSE);

$^W = 1;

$VERBOSE = 1 if !defined $VERBOSE;

if (BBBikeServer::running()) {
    # adjust filenames (from relative to absolute)
    my($center, $centerc, $from, $to, $do_help);
    if (!GetOptions("center=s"  => \$center,
		    "centerc=s" => \$centerc,
		    "from=s"    => \$from,
		    "to=s"      => \$to,
		    "v|verbose!" => \$VERBOSE,
		    "h|?|help"  => \$do_help,
		   )) {
	warn "Some arguments will be ignored...\n";
    }

    if ($do_help) {
	usage();
    }

    my @argv;
    if (defined $center) {
	push @argv, "-center", $center;
    }
    if (defined $centerc) {
	push @argv, "-centerc", $centerc;
    }
    if (defined $from) {
	push @argv, "-from", $from;
    }
    if (defined $to) {
	push @argv, "-to", $to;
    }
    for(my $i=0; $i<=$#ARGV; $i++) {
	my $arg = $ARGV[$i];
	if ($arg !~ /^-/) {
	    eval q{
		   require File::Spec;
		  };
	    if (!$@) {
		if (!File::Spec->file_name_is_absolute($arg)) {
		    $arg = File::Spec->rel2abs($arg);
		}
	    } else {
		warn "File::Spec is not available, cannot check for relative path names!";
	    }
	}
	push @argv, "-routefile", $arg;
    }
    warn "Send to bbbike server: @argv\n" if $VERBOSE;
    exit 0 if !@argv;
    $BBBikeServer::VERBOSE = $VERBOSE;
    exit 0 if (BBBikeServer::send_to_server(-argv => \@argv));
    exit 1;
}

my @saveargs = @ARGV;
my $startserver = 1;
# XXX be quiet...
GetOptions("startserver!" => \$startserver);
if ($startserver) {
# remove -startserver option, if necessary XXX
    warn "No server process found, restarting bbbike...\n" if $VERBOSE;
    @ARGV = @saveargs;
    unshift @ARGV, "-server";
    system($^X, "$FindBin::RealBin/bbbike", @ARGV);
}

sub usage {
    die <<EOF;
usage: $0 [-center street] [-centerc x,y] [-from street -to street] file ...
EOF
}

__END__
