#!/usr/bin/perl -w
# $Id$
# read email with request from stdin and process it

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

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

# ---------------------------------------------------------------
use File::Basename;
use File::Copy;
use Cwd;

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

sub report_fatal($)
{
  my $msg = shift;
  cleanup();
  open(M, "| /usr/sbin/sendmail -t") or die("/usr/sbin/sendmail not found");
  #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("problem while sending email");
  exit 0;
}
# ---------------------------------------------------------------

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

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

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

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

$oldcwd = Cwd::getcwd();

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

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

$specdir = File::Basename::basename($spec,('.spec'));
if (system("cvs -d :pserver:cvs\@cvs.pld-linux.org:/cvsroot get $branch \"packages/$specdir/$spec\" >/dev/null 2>&1") != 0) {
  chdir($oldcwd);
  report_fatal("cannot cvs get $spec at $branch")
}

chdir($oldcwd);

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

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

File::Copy::move("tmp/$id/to-spool", "$spool_dir/$id") or die("move failed: $!");

cleanup();

exit(0);

