#!/usr/bin/env perl

# M5 build setup script.

# There are two types of build configuration files: base files, in the
# 'base' directory, that describe base configurations; and option
# files, in the 'opt' directory, that describe configuration options.
# This script takes the name of a build, consisting of one of the
# former and zero or more of the latter, separated by dots, and sets
# up a corresponding build directory.

$USAGE = "usage: $0 [-d <build dir>] <base config>[.<option>]*\n";

use Getopt::Std;
use Cwd;

getopts("d:") or die $USAGE;

# remaining arg is config name e.g. 'base.opt1.opt2'
$BUILDDIR = shift or die "error: missing arg.\n$USAGE";

# shouldn't be any other args
die "error: extra args.\n$USAGE" if (scalar(@ARGS) != 0);

($BASEFILE, @OPTFILES) = split('\.', $BUILDDIR);

$BASEFILE = "base/$BASEFILE";
die "File $BASEFILE not found.\n" if (! -f $BASEFILE);

@OPTFILES = map { "opt/$_" } @OPTFILES;

foreach $f (@OPTFILES) {
    die "File $f not found.\n" if (! -f $f);
}

chomp($HOSTNAME = `hostname -s`);
chomp($OSNAME = `uname -s`);
chomp($ARCHNAME = `uname -m`);
$SETUPDIR = $ENV{PWD};
if (!scalar($SETUPDIR)) {
	chomp($SETUPDIR = `pwd`);
}
chomp($SRCDIR = `dirname $SETUPDIR`);
chomp($BASEDIR = `dirname $SRCDIR`);
$EXTDIR = "$BASEDIR/ext";

$buildtmp = $opt_d || "../build";

if (! -e $buildtmp) {
    mkdir $buildtmp or die "Can't create $buildtmp: $!";
}
chop($BUILDBASE = `cd $buildtmp; pwd`);

$SRCLINK = "$BUILDBASE/src";
$EXTLINK = "$BUILDBASE/ext";

if (! -e $SRCLINK) {
    symlink($SRCDIR, $SRCLINK) or die "Can't create $SRCLINK: $!";
}
else {
    if (Cwd::abs_path(readlink($SRCLINK)) ne Cwd::abs_path($SRCDIR)) {
	die "error: $BUILDBASE was created for a different source directory.\n";
    }
}

if(! -e $EXTLINK) {
    symlink($EXTDIR, $EXTLINK) or die "Can't create $EXTLINK symlinked to $EXTDIR: $!";
}
else
{
    if(Cwd::abs_path(readlink($EXTLINK)) ne Cwd::abs_path($EXTDIR)) {
    die "error: $BUILDBASE was created for a different source direcotry.\n";
    }
}

$BUILDDIR = "$BUILDBASE/$BUILDDIR";

if ( -e $BUILDDIR) {
    $EXISTS = 1;
}
else {
    mkdir $BUILDDIR or die "error: could not create $BUILDDIR: $!";
}

open SETUP, ">$BUILDDIR/Makefile" or die "Can't open $BUILDDIR/Makefile: $!";

print SETUP <<EOF;
# Automatically generated Makefile

CONFIG_HOSTNAME=$HOSTNAME
CONFIG_OSNAME=$OSNAME
CONFIG_ARCHNAME=$ARCHNAME

SRCDIR=\$(shell readlink ../src)
EXTDIR=\$(shell readlink ../ext)
BUILDBASE=$BUILDBASE
BUILDDIR=$BUILDDIR
EOF

local $/; # undef local $/: slurp in whole files

foreach $f ($BASEFILE, @OPTFILES) {
    print SETUP "# The following options come from $f\n";
    open FILE, "$f" or die "Can't open $f: $!";
    print SETUP <FILE>;
    close FILE;
    print SETUP "\n";
}

print SETUP <<EOF;
# Now we get the real makefile stuff
include \$(SRCDIR)/setup/makefile
EOF

close SETUP;

if ($EXISTS) {
    print "The build directory exists; don't forget to make clean.\n";
}
