#!/usr/bin/perl -w

use strict;
use warnings;
use File::Basename;

my $usage_short = "Usage: rput [--help|-c <configfile> <rpmfile1> .. <rpmfileN>\n";

my $cmd = shift(@ARGV) || '--help';
my $dest = '';
my $post = '';
my $any = 0;
my @allups = ();

select STDOUT; $| = 1;
select STDERR; $| = 1;

while ($cmd) {
    if ($cmd =~ m/^--help$/i) {
        help();
        exit(0);
    } elsif ($cmd =~ m/^-c$/i) {
        my $cfg = shift(@ARGV) || die $usage_short;
        readcfg($cfg);
    } else {
        if (-f $cmd) {
            upload($cmd);
        } else {
            die "$cmd does not exist.\n";
        }
    }
    $cmd = shift(@ARGV);
}
if ($any) {
    postupload();
}
exit(0);

sub help {
    print $usage_short;
    print << "EOF"
    --help                         Print this text.
    -c <configfile>                Specify config file.
EOF
}

sub readcfg {
    my $cfg = shift();
    open(F, "<$cfg") || die "Can't read $cfg: $!\n";
    while (<F>) {
        chomp;
        next if (/^#.*/);
        if (/^\s*dest\s*=\s*(.*)$/) {
            $dest = $1;
        }
        if (/^\s*post_upload_command\s*=\s*(.*)$/) {
            $post = $1;
        }
    }
    close(F);
}

sub upload {
    my $rpm = shift;
    if ($dest ne '') {
        chkrun("rsync -q $rpm $dest");
        $any = 1;
        push(@allups, $rpm);
        return;
    }
    die "dest is undefined.\n";
}

sub postupload {
    if ($post ne '') {
        my $postp = join(' ', @allups);
        my $postcmd = $post;
        $postcmd =~ s/%f/$postp/g;
        chkrun($postcmd);
    }
}

sub chkrun {
    my $cmd = shift;
    system($cmd);
    if ($? == -1) {
        die "failed to execute: $!\n";
    }
    elsif ($? & 127) {
        die sprintf "child died with signal %d, %s coredump\n",
        ($? & 127), ($? & 128) ? 'with' : 'without';
    }
    else {
        if (0 ne ($? >> 8)) {
            die sprintf("child exited with value %d\n", $? >> 8);
        }
    }
}
