#!/usr/bin/perl

use strict;
use warnings;
no warnings 'uninitialized';

die "You must be root to build the RPM\n" if ($>);

my $specfile   = 'Shell-EnvImporter.spec';
my $sourcefile = &get_sourcefile_name($specfile);

print "SOURCEFILE: $sourcefile\n";

&build_rpm($sourcefile, $specfile);

system("rpmbuild -ba $specfile");

unlink($sourcefile);


##############################################################################
###############################  Subroutines  ################################
##############################################################################

###############
sub build_rpm {
###############
  my $sourcefile  = shift;
  my $specfile    = shift;
  my $excludefile = "/var/tmp/build_rpm_exclude.$$";

  # Build a source tarball, excluding CVS directories
  system("find . -name '.svn' > $excludefile");
  open(EX, ">>$excludefile");
  print EX "$specfile\n";
  print EX "build_rpm\n";
  close(EX);

  my $rv     = system("tar -czf $sourcefile --exclude-from $excludefile .");
  my $errmsg = $!;

  unlink($excludefile);

  die "Couldn't create $sourcefile: $errmsg" if ($rv);

}



#########################
sub get_sourcefile_name {
#########################
  my $specfile = shift;

  my $tmpdir   = $ENV{'TMP'} || '/var/tmp';
  my $tmpfile  = "$tmpdir/build_rpm.$$";
  my $tag      = 'SOURCEFILE';
  my $sourcefile;

  open(SPEC, $specfile) or die "Couldn't open $specfile: $!";
  open(TMP, ">$tmpfile") or die "Couldn't create $tmpfile: $!";
  while (<SPEC>) {
    last if (/^%prep/);
    print TMP $_;
  }
  close(SPEC);

  print TMP "%build\n";
  print TMP "echo ", join(":", $tag, '%{S:0}'), "\n";
  print TMP "exit -1\n";
  close(TMP);

  open(RPMBUILD, "rpmbuild -bc $tmpfile --short-circuit 2>&1 |")
    or die "Couldn't spawn rpmbuild: $!";

  while (<RPMBUILD>) {
    next if (/^Executing/);
    next if (/^\+/);
    if (/^$tag/) {
      chomp;
      $sourcefile = (split(/:/, $_, 2))[1];
      last;
    } else {
      warn("Unexpected output from rpmbuild: $_");
    }
  }
  close(RPMBUILD);

  unlink($tmpfile);

  return $sourcefile;
}
