#!/usr/bin/perl
# Copyright (c) 2010 David Sugar, Tycho Softworks
#
# This file is free software; as a special exception the author gives
# unlimited permission to copy and/or distribute it, with or without
# modifications, as long as this notice is preserved.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

strict;

use Net::FTP;
use File::Basename;

my $email = $ENV{GNUEMAIL};
my $ftp = Net::FTP->new("ftp-upload.gnu.org");
$ftp->login("ftp");
$ftp->cwd("/incoming/ftp");
$ftp->binary();

if ($email eq "") {
    $email = $ENV{USER} . "@gnu.org";
}

foreach(@ARGV) {
    ($file, $dir, $ext) = fileparse($_, qr/\.\D.*/);

    if($ext ne ".tar.gz") {
        print "*** gnudist: $file$ext: invalid file\n";
        next;
    }

    unless(-e $_) {
        print "*** gnudist: $file$ext: doesn't exist\n";
        next;
    }

    my $tarball = $_;
    my $sigfile = "$tarball.sig";
    my $directive = "$tarball.directive.asc";
    my $tmpflag = 0;

    unless(-e $sigfile) {
        my $localdirective = "$dir/directive";
        unless(-e $localdirective) {
            print "*** gnudist: $dir: directive missing\n";
            next;
        }
        $tmpdirective="/tmp/$file$ext.directive";
        $tmptarball="/tmp/$file$ext";
        $sigfile="/tmp/$file$ext.sig";
        $directive="/tmp/$file$ext.directive.asc";
        unlink $directive;
        unlink $sigfile;
        ++$tmpflag;
        system("cp $tarball $tmptarball");
        system("cp $localdirective $tmpdirective");
        system("gpg --clearsign -u $email $tmpdirective");
        system("gpg -b -u $email $tmptarball");
    }

    print "uploading $file$ext...\n";
    $ftp->put("$tmptarball");
    $ftp->put("$sigfile");
    $ftp->put("$directive");

    if(tmpflag > 0) {
        unlink $sigfile;
        unlink $directive;
        unlink $tmpdirective;
        unlink $tmptarball;
    }
}

$ftp->quit();

