#!/usr/bin/perl

use strict;

use Getopt::Std;

my @VALID_TARGETS = qw(rps01.royaltyshare.com);
my $RDIST         = '/usr/bin/rdist -P /usr/bin/ssh -c';

my %opt;
getopts( 't:', \%opt );

my $CONFIG = _get_defaults();

my $target = $opt{t} || $CONFIG->{TARGET};
die "invalid target: '$target'\n" unless _valid_target($target);
die "$0 file1 file2 fileN [-t <target_server_name>]" unless $ARGV[0];

my @fileList = ();
foreach my $file (@ARGV) {
    $file =~ s#^\./##;
    substr( $file, 0, 0 ) = $ENV{PWD} . '/' unless ( $file =~ m/^\// );
    unless ( -e $file ) {
        print "can't find $file\n";
        next;
    }
    push( @fileList, $file );
}
die "nothing to do\n" unless @fileList;

printf( "\nYou are about to update/install the following file(s) on %s:\n\n%s\n\nOK? (y/n):", $target, join( "\n", @fileList ) );

my $confirm = <STDIN>;
die "cancelled\n" unless ( $confirm =~ m/^y/i );

my $CMD = sprintf( "%s %s %s\n", $RDIST, join( ' ', @fileList ), $target );
system($CMD);

sub _get_defaults {
    return undef unless open( DISTRC, "$ENV{HOME}/.rdistrc" );
    my %config;

    while (<DISTRC>) {
        chop;
        m/^(\w+)=(.+)$/;
        $config{ uc($1) } = $2;
    }
    close(DISTRC);

    return \%config;
}

sub _valid_target {
    my $target = shift;

    map { return 1 if ( $_ eq $target ) } @VALID_TARGETS;
    return 0;

    #my $count = 0;
    #my $match = 0;

    #foreach my $t(split /\s+/, $target)
    #{
    #$count++;
    #map { $match++ if ($_ eq $t) } @VALID_TARGETS;
    #}

    #return $match == $count ? 1 : 0;
}

