#!/usr/bin/env perl
#!/usr/local/bin/perl
#
# A script to execute remote ups commands.
#
# Usage: updupr <URL> <command> [arguments]
#
# e.g: updupr list -h fndapg exmh -f IRIX -g current
#      updupr hi -h fndapg, will just check if server is there.
#      updupr env -h fndapg, will list the server host environment.
#
#      using a html browser, it corresponds to:
#   
#      http://fndapg.fnal.gov/cgi-bin/ups.cgi?list&exmh&-f&IRIX&-g&current
#      http://fndapg.fnal.gov/cgi-bin/ups.cgi?hi
#      http://fndapg.fnal.gov/cgi-bin/ups.cgi?env
#

BEGIN {

  die "UPD_DIR is not defined ... we are quitting.\n" unless ( $ENV{UPD_DIR} );
  unshift @INC, "$ENV{UPD_DIR}/src";
}

use strict;
use upderr;
use updups;
use updupr;
use updgbl;

my $g_prog = 'updupr';

# check arguments

usage() if ( $ARGV[0] eq "-?" );

# parse command line (mainly just to extract '-h url', '-vvv')

my $opt_h = '';
my $ups_cmd = '';
my $verbose = 0;
my $opt_H = 0;

while ( @ARGV ) {

  $_ = shift @ARGV;

  if ( /^-h/ ) { $opt_h = shift; }
  elsif ( /^-v/ ) { $ups_cmd .= "$_ "; $verbose = length( $_ ) -1; }
  elsif ( /^-\?/ ) { usage(); }
  else {

    # check if -H option is passed on command line, so we don't
    # overwrite it

    $opt_H = 1 if ( /^-H/ );

    # an empty variable should be ""

    $_ = "\"\"" unless ( $_ );

    # if variable contains white spaces, add quotes

    if ( /\s/ ) {
      my $tmp = "\"";
      $tmp .= $_ . "\"";
      $_ = $tmp;
    }

    # append to ups command

    $ups_cmd .= "$_ "; 
  }
}
chop $ups_cmd;

upderr_setverbose( $verbose );

# set a default host if not passed

if ( ! $opt_h ) {
  $opt_h = $g_default_remote_node;
  upderr_log(2,"Defaulting distribution node to $opt_h\n");
}

# set -H if not passed

if ( ! $opt_H ) {
  my $flavor;

  if ( !updups_flavor( "local", "-3", \$flavor ) ) {
    die( "Unable to get local flavor, stopped" );
  }
  
  $ups_cmd .= " -H $flavor";
}

my $ret_code = updupr_oxc( $opt_h, $ups_cmd );

upderr_get();

upderr_log(2,"got return code of $ret_code from updupr_oxc\n");
exit($ret_code>>8);

sub usage { die "Usage: $g_prog <command> -h <URL> [ups arguments] [-vvv] [-?]\n"; } 

1;
