#!/usr/bin/perl -w

use Getopt::Long;
use Cwd;

$release = 1;
$rpmbuilddir = '/usr/src/rpm';
$arch = 'i386';

  #  Enable root in Slackware to build gtk/gnome stuff
$ENV{PATH} .= ':/opt/gnome/bin';

$startdir = cwd();

die "Must be root to make the RPM\n" if $>;
die "Cannot find build dir $rpmbuilddir\n" unless -d $rpmbuilddir;
die "VERSION file missing\n" unless -f 'VERSION';

Getopt::Long::Configure('bundling');
unless(GetOptions('release|r=i', \$release)) { die }

if (open F, 'wmtheme.spec.in') {
  local $/ = undef;
  $specin = <F>;
  close F;
} else {
  die "Can't open wmtheme.spec.in: $!\n";
}

chomp($version = `cat VERSION`);

unless (-e "wmtheme-$version.tar.gz") {
  system('make', 'dist') and
    die "Error making dist\n";
}

print "[make-rpm] executing 'make speclist'\n";

system('make', 'speclist', 'prefix=/usr') and
  die "Error making speclist\n";

if (open F, 'spec-file-list') {
  local $/ = undef;
  $files = <F>;
  close F;
} else {
  die "Can't open spec-file-list: $!\n";
}

print "[make-rpm] generating wmtheme.spec\n";

$specin =~ s/\@VERSION\@/$version/gs or die "No \@VERSION\@ in spec.in?\n";
$specin =~ s/\@RELEASE\@/$release/gs or die "No \@RELEASE\@ in spec.in?\n";
$specin =~ s/\@FILES\@/$files/gs or die "No \@FILES\@ in spec.in?\n";

open F, ">$rpmbuilddir/SPECS/wmtheme.spec" or
  die "Can't write $rpmbuilddir/SPECS/wmtheme.spec: $!\n";
print F $specin;
close F;

system('cp', "wmtheme-$version.tar.gz", "$rpmbuilddir/SOURCES") and
  die "Error copying wmtheme-$version.tar.gz to $rpmbuilddir/SOURCES\n";

chdir "$rpmbuilddir/SPECS" or die "Can't chdir $rpmbuilddir/SPECS: $!\n";

print "[make-rpm] executing 'rpm -ba wmtheme.spec'\n";

system('rpm', '-ba', 'wmtheme.spec') and die "Error building RPM.\n";
system('cp', "$rpmbuilddir/RPMS/$arch/wmtheme-$version-$release.$arch.rpm",
  $startdir) and die "Error copying rpm to $startdir\n";

print "[make-rpm] RPM build successful\n";

