#!/usr/bin/perl

# Copyright (C) 1999-2003, Matevz Tadel. All rights reserved.
# This file is part of GLED, released under GNU General Public License version 2.
# For the licensing terms see $GLEDSYS/LICENSE or http://www.gnu.org/.

use Carp;
use lib ".";
use ParseConfig;

$def_cfg = "build.rc";

my $cfg_parser = new ParseConfig(-defcfg=>$def_cfg, -useenv=>1);
$cfg_parser->parse();

if($HELP) {
  print "usage: build.pl <options>\n";
  print "Options:\n";
  print `cat $def_cfg`;
  exit 0;
}

$TOPDIR   = "$ENV{PWD}";
$INSTDIR  = "$TOPDIR/inst/$BUILDNAME";
$BUILDDIR = "$TOPDIR/build/$BUILDNAME";

$EXT_DISTDIR  = "$TOPDIR/external/dist";
$EXT_PREBUILTDIR = "$TOPDIR/external/prebuilt";

$LS_SRCDIR  = "$TOPDIR/libsets/src";
$LS_DISTDIR = "$TOPDIR/libsets/dist";

$DEMODIR = "$TOPDIR/demos";

$META_DISTDIR = "$TOPDIR/packs";

$VER_RE = '\d+\.\d+\.\d+\w*';
$TAR_RE = '(?:tar\.gz|tgz)';

do "$CONFIG" or die "Could not open config file '$CONFIG'";
die "No external src directory" unless -d "$TOPDIR/external/src";
die "No libset src directory" unless -d "$TOPDIR/libsets/src";
die "No internal directory" unless -d "$TOPDIR/internal";
die "Buildname should be set" unless $BUILDNAME;

exec_or_die("rm -rf $BUILDDIR $INSTDIR");
exec_or_die("mkdir -p $BUILDDIR $INSTDIR");

########################################################################

sub exec_or_die {
  my $cmd = shift;
  my $ret = `$cmd`;
  croak "$cmd died" if $?;
  return $ret
}

sub system_or_die {
  my $cmd = shift;
  system "$cmd" and die "$cmd died";
}

sub slurp_dir {
  my $dir = shift;
  opendir D, $dir;
  my @files = readdir D;
  closedir D;
  @files = grep { -f "$dir/$_" and !/^\./ } @files; # grep out .files, . and ..
  return @files;
}


########################################################################

sub deduce_package_stuff {
  my $pkg = shift;
  
  my @files = grep { /^${pkg}-${VER_RE}(?:-src)?\.${TAR_RE}/ } @FILES_IN_SRC;

  if($#files != 0) {
    croak "source tarball for $pkg not found" if $#files < 0;
    croak "several tarballs found for $pkg:\n\t" . join("\n\t", @files) . "\n";
  }
  my $file = $files[0];
  $file =~ m/$pkg-($VER_RE)(?:-src)?\.$TAR_RE/;
  return ($file, $1);
}

sub deduce_dir_name {
  my $tar = shift;
  open F, "tar tzf $tar|" or die "failed listing tar file $tar";
  my $dir = <F>; chomp $dir;
  close F;
  $dir =~ s!/+$!!o;
  return $dir;
}

########################################################################


%smart_default =
  (
   'configure' => './configure --prefix=%i/%p',
   'build'     => 'make',
   'install'   => 'make install'
  );

sub smart_exec {
  my ($pkg, $x, $what) = @_;

  my @lines;
  if(not exists($x->{$what})){ push @lines, $smart_default{$what}; }
  elsif(not ref($x->{$what})) { push @lines, $x->{$what}; }
  elsif(ref($x->{$what}) eq "ARRAY") { @lines = @{$x->{$what}}; }
  else { die "'$what' of $pkg should be null, scalar or array ref";}

  for $l (@lines) {
    $l =~ s/%i/$INSTDIR/g;
    $l =~ s/%p/$pkg/g;
    $l =~ s/%v/$x->{specs}{version}/g;
    system_or_die($l);
    
  }
  $x->{specs}{$what} = join("\n", @lines);
}

########################################################################

print '#' x 80 ."\n";
print "# Building external software\n";
print '#' x 80 ."\n\n";

print '#' x 10 . " Scanning packages ...\n";

@FILES_IN_SRC = slurp_dir("$TOPDIR/external/src");
for $p (@$Packages) {
  die "Package $p not in Packalog" unless defined $Packalog->{$p};
  my ($f, $v) = deduce_package_stuff($p);
  my $d = deduce_dir_name("$TOPDIR/external/src/$f");
  printf "%-12s %-28s %-10s %s\n", $p, $f, $v, $d;
  $Packalog->{$p}{'specs'} =
    { 'srctarfile' => "$TOPDIR/external/src/$f",
      'bintarfile' => "$EXT_DISTDIR/$p-$v-${BUILDNAME}.tar",
      'bintarfile_gz' => "$EXT_DISTDIR/$p-$v-${BUILDNAME}.tar.gz",
      'version' => $v,
      'dirname' => $d,
    };
}

if($SKIP_EXTERNAL) {
  print "\n" . '#' x 10 . " Skipping build of external software ...\n\n";
  goto external_build_end;
}

exec_or_die("rm -rf $EXT_DISTDIR/*${BUILDNAME}*");
exec_or_die("mkdir -p $EXT_DISTDIR");

print '#' x 10 . " Attacking packages ...\n";

for $p (@$Packages) {
  my $x = $Packalog->{$p};

  print '#' x 8 . " Unpacking $p ...\n";

  chdir "$BUILDDIR";
  exec_or_die("tar xzf $x->{specs}{srctarfile}");
  chdir "$x->{specs}{dirname}" or die "couldn't cd into build dir of $p";

  print '#' x 8 . " Configuring $p ...\n";
  smart_exec($p, $x, 'configure');

  print '#' x 8 . " Building $p ...\n";
  smart_exec($p, $x, 'build');

  print '#' x 8 . " Installing $p ...\n";
  smart_exec($p, $x, 'install');
}


print '#' x 10 . " Preparing binary tarballs ...\n";

open  TOPBLA,">$EXT_DISTDIR/readme_${BUILDNAME}_auto" or
  die "can't create build readme";
print TOPBLA "Author   : $AUTHOR\n";
print TOPBLA "Buildname: $BUILDNAME\n";
print TOPBLA "uname -a : " . `uname -a`;
print TOPBLA "date     : " . `date`;
print TOPBLA "Package listing:\n";

for $p (@$Packages) {
  my $x = $Packalog->{$p};

  print '#' x 8 . " Munching $p ...\n";
  chdir "$INSTDIR/$p";
  open  BLA, ">readme_${p}_auto" or die "can't create readme for $p"; 
  print BLA "$p-$x->{specs}{version}, auto-built as an external package for GLED.\n\n";
  print BLA $x->{comment} . "\nHomepage: " . $x->{homepage} . "\n";
  print BLA "\nBuild details:\n";
  print BLA "Builder  : $AUTHOR\n";
  print BLA "Buildname: $BUILDNAME\n";
  print BLA "uname -a : " . `uname -a`;
  print BLA "date     : " . `date`;
  print BLA "\n";
  print BLA "configure: ", $x->{specs}{configure}, "\n";
  print BLA "build    : ", $x->{specs}{build}, "\n";
  print BLA "install  : ", $x->{specs}{install}, "\n";
  close BLA;

  print TOPBLA "$p-$x->{specs}{version}\n";

  system_or_die("tar cf $x->{specs}{bintarfile} *");

  unless($KEEP_EXTERNAL) {
    print '#' x 8 . " Removing build & install directories for $p ...\n";
    chdir "$INSTDIR";  exec_or_die("rm -rf $p");
    chdir "$BUILDDIR"; exec_or_die("rm -rf $x->{specs}{dirname}");
  }
}
close TOPBLA;

print '#' x 10 . " Compressing binary tarballs ...\n";
chdir("$EXT_DISTDIR");
system_or_die("gzip -f -9 *.tar");

external_build_end:


########################################################################
### Libset building
########################################################################

print '#' x 80 ."\n";
print "# Building Libsets\n";
print '#' x 80 ."\n\n";

if($SKIP_LIBSET) {
  print '#' x 10 . " Skipping build of libsets ...\n\n";
  goto libset_build_end;
}

$GLED_DIR = "$BUILDDIR/gled-$GledVersion";
exec_or_die("rm -rf $GLED_DIR $LS_DISTDIR/*${BUILDNAME}*");
exec_or_die("mkdir -p $GLED_DIR $LS_DISTDIR");
chdir $GLED_DIR;


print '#' x 10 . " Unpacking libsets ...\n";

exec_or_die("tar xzf $TOPDIR/internal/gled-build.tar.gz");
open LSL, ">build_libsets";
for $ls (@$LibSets) {
  print '#' x 4 . " Unpacking $ls [$LS_SRCDIR/${ls}-src.tar.gz]\n";
  exec_or_die("tar xzf $LS_SRCDIR/${ls}-src.tar.gz");
  print LSL "$ls\n";
}
close LSL;


print '#' x 10 . " Unpacking external binaries ...\n";

exec_or_die("mkdir -p external");
chdir "external";
for $p (@$ExternalPackages) {
  print '#' x 4 . " Unpacking $p [$Packalog->{$p}{specs}{bintarfile_gz}]\n";
  exec_or_die("tar xzf $Packalog->{$p}{specs}{bintarfile_gz}");
}
chdir $GLED_DIR;

open BS, ">build_script";
print BS<<"fnord";
. binenv.sh
./configure --ext=$GLED_DIR/external || exit 1
./mecca || exit 1
fnord

for $ls (@$LibSets) {
  print BS "BIN_DIST_TAR=$LS_DISTDIR/${ls}-${BUILDNAME}.tar make -C $ls bin_dist || exit 1\n";
}
close BS;
chmod 0755, "build_script";


print '#' x 10 . " Running build script ...\n";

system_or_die("./build_script");
chdir $TOPDIR;

unless($KEEP_LIBSETS) {
  print '#' x 8 . " Removing Gled build directory ...\n";
  exec_or_die("rm -rf $BUILDDIR/gled-$GledVersion");
}

print '#' x 10 . " Compressing binary libsets ...\n";

exec_or_die("gzip -f -9 $LS_DISTDIR/*-${BUILDNAME}.tar");

libset_build_end:

########################################################################
### Packing MetaPackages
########################################################################

print '#' x 80 ."\n";
print "# Preparing MetaPackages\n";
print '#' x 80 ."\n\n";

if($SKIP_META) {
  print '#' x 10 . " Skipping build of meta packages ...\n\n";
  goto meta_build_end;
}

for $mp (@$MetaPackages) {
  print '#' x 10 . " Meta packing $mp ...\n";

  my $pd = $Metalog->{$mp};

  chdir $BUILDDIR;
  exec_or_die("rm -rf $mp");

  my $ext_dir = $pd->{shallow_externals} ? "$mp/$pd->{dirname}" :
                                           "$mp/$pd->{dirname}/external";
  exec_or_die("mkdir -p $ext_dir");

  print '#' x 6 . " Unpacking externals ...\n";
  chdir $ext_dir;
  for $p (@{$pd->{packages}}) {
    system_or_die("tar xzf $Packalog->{$p}{specs}{bintarfile_gz}");
  }
  chdir ".." unless $pd->{shallow_externals};

  print '#' x 6 . " Unpacking libsets ...\n";
  for $ls (@{$pd->{libsets}}) {
    system_or_die("tar xzf $LS_DISTDIR/${ls}-${BUILDNAME}.tar.gz");
  }

  print '#' x 6 . " Unpacking freetars ...\n";
  for $f (@{$pd->{freetars}}) {
    system_or_die("tar xzf $f");
  }

  print '#' x 6 . " Compressing ...\n";
  chdir "..";
  system_or_die("tar cf ${META_DISTDIR}/${mp}-${BUILDNAME}.tar $pd->{dirname}");
  system_or_die("gzip -f -9 ${META_DISTDIR}/${mp}-${BUILDNAME}.tar");

  unless($KEEP_META) { 
    chdir "..";
    exec_or_die("rm -rf $mp");
  }
  print "\n";
}

open  TOPBLA,">${META_DISTDIR}/readme_${BUILDNAME}_auto" or
  die "can't create meta build readme";
print TOPBLA "Author   : $AUTHOR\n";
print TOPBLA "Buildname: $BUILDNAME\n";
print TOPBLA "date     : " . `date`;
print TOPBLA "Package listing:\n\n";

for $mp (@$MetaPackages) {
  my $pd = $Metalog->{$mp};
  print TOPBLA "MetaPackage $mp:\n",
  "  External: ", join(", ", @{$pd->{packages}}), "\n",
  "  Libsets: ", join(", ", @{$pd->{libsets}}), "\n",
  "  Freetars: ", join(", ", map { s/$TOPDIR//; $_ } @{$pd->{freetars}}), "\n\n"; 
}

close TOPBLA;

meta_build_end:
