#!/usr/bin/perl -w
# -*- perl -*-

#
# $Id: make_bundle,v 1.3 2003/01/16 14:29:11 eserte Exp $
# Author: Slaven Rezic
#
# Copyright (C) 2001 Online Office Berlin. All rights reserved.
# Copyright (C) 2002 Slaven Rezic.
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, see the file COPYING.
#
# Mail: slaven@rezic.de
# WWW:  http://we-framework.sourceforge.net
#

# build all WE_Framework related modules
use FindBin;
use File::Spec;
use Cwd;
use Getopt::Long;

my $k;
my $onlytest;

if (!GetOptions("k" => \$k,
		"onlytest|testonly" => \$onlytest)) {
    die "usage: $0 [-k] [-testonly|-onlytest]";
}

sub _save_pwd (&);

my @bundle_dirs = qw(WE_Framework WE_Framework_FTP Tk-OO WE_Tk_Framework);

my $workdir = File::Spec->catpath($FindBin::RealBin,
				  File::Spec->updir,
				  File::Spec->updir,
				 );
if (!-d $workdir) {
    die "Strange: cannot find directory $workdir";
}
chdir $workdir or die "Cannot chdir to $workdir: $!";
$workdir = cwd;

my @f = glob("*");
my %f = map {($_=>1)} @f;

my @missing;
foreach my $dir (@bundle_dirs) {
    push @missing, $dir if (!exists $f{$dir});
}
if (@missing) {
    print STDERR "The following directories are missing in $workdir: @missing.
Do you nevertheless want to continue? (y/N) ";
    my($yn) = scalar <STDIN>;
    exit unless ($yn =~ /^y/i);
}

my @blib;
foreach my $dir (@bundle_dirs) {
    _save_pwd {
	print STDERR "Building $dir ...\n";

	$ENV{BATCH} = "yes";

	chdir $dir or die "Cannot chdir to $dir: $!";

	my @blib_args = map { "-Mblib=$_" } @blib;

	# XXX PERL5OPT would be the "right thing", but seems to be
	# badly supportedon perl < 5.7.2
	# $ENV{PERL5OPT} = join(" ", @blib_args);

	my $perl = "FULLPERL=$^X";
	if (@blib_args) { $perl .= " " . join(" ", @blib_args) }

	my @cmd = ($^X, @blib_args, "Makefile.PL", $perl);
	system @cmd; die "While executing @cmd" if $?/256 != 0 && !$k;
	if (!$onlytest) {
	    system("make"); die "While make" if $?/256 != 0 && !$k;
	}
	system("make", "test"); die "While make test" if $?/256 != 0 && !$k;

	push @blib, "$workdir/$dir";
    };
}

# REPO BEGIN
# REPO NAME save_pwd /home/e/eserte/src/repository 
# REPO MD5 013f179fd8b36baacb5c97f44caa8ca2

=head2 _save_pwd(sub { ... })

=for category File

Save the current directory and assure that outside the block the old
directory will still be valid.

=cut

sub _save_pwd (&) {
    my $code = shift;
    require Cwd;
    my $pwd = Cwd::cwd();
    eval {
	$code->();
    };
    my $err = $@;
    chdir $pwd or die "Can't chdir back to $pwd: $!";
    die $err if $err;
}
# REPO END


__END__
