#!/usr/bin/perl
# read email with request from stdin and process it

$spool_dir = "./spool";
$commits_list = "pld-cvs-commit\@pld-linux.org";

$spec = undef;
$branch = "";
$from = undef;
$flags = "";

$id = `uuidgen`;
chomp $id;
$id = rand if (!defined $id or $id eq "");

while (<STDIN>) {
  chomp;
  /^X-Spec: ([\+a-zA-Z0-9_\-]+\.spec)/i and $spec = $1;
  /^X-Branch: ([a-zA-Z0-9_\-]+)/i and $branch = $1;
  /^X-Login: ([a-zA-Z0-9_]+)/i and $from = $1;
  /^X-Flags: ([a-zA-Z0-9\-_ ]+)/i and $flags = $1;
}

die "ill-formed request" if (!defined $from);

report_fatal("bad spec name") if (!defined $spec);

mkdir("tmp/$id") or die;
chdir("tmp/$id");

$branch = "" if ($branch eq "HEAD");
$branch = "-r \"$branch\"" if ($branch ne "");

if (system("cvs get $branch \"SPECS/$spec\" >/dev/null 2>&1") != 0) {
  chdir("../..");
  report_fatal("cannot cvs get $spec at $branch")
}

chdir("../..");

open(S, "> tmp/$id/to-spool");
print S "$from\@pld-linux.org\n";
print S "$flags\n";
close(S);

if (system("perl ./specparser.pl \"tmp/$id/SPECS/$spec\" >> tmp/$id/to-spool") != 0) {
  report_fatal("cannot parse $spec ($branch)")
}

rename("tmp/$id/to-spool", "$spool_dir/$id");

cleanup();

exit(0);

sub report_fatal($)
{
  my $msg = shift;
  cleanup();
  open(M, "| /usr/sbin/sendmail -t") or die;
  #open(M, "| cat") or die;
  my $version = '$Id$';
  print M <<EOF
From: $from <$from\@pld-linux.org>
To: $commits_list
Cc: $from\@pld-linux.org
Message-ID: <$id\@distfiles.pld-linux.org>
Subject: DISTFILES: ERROR fetching sources for $spec ($branch)
X-distfiles-program: request-handler.pl
X-distfiles-version: $version

$msg

-- 
Virtually Yours: distfiles.
EOF
;
  close(M) or die;
  exit 0;
}

sub cleanup()
{
  system("rm -rf tmp/$id");
}
