#!/usr/bin/perl -s

require "pwd.pl";

&initpwd;

###########################################################################
# Variables that configure the operation of this script
###########################################################################

$product = "Polyflow-Applications";

###########################################################################
# find out where the setup script lives
###########################################################################

$0 =~ /(.*)setup$/;
$srcdir = $1;			# ends with a slash unless empty

$pwd = $ENV{"PWD"};
# a relative path is anything that doesn't start with a "/"
if ($srcdir !~ /^\//) {
    # resolve relative path into absolute path
    $srcdir = "$pwd/$srcdir";	# ends with a slash
}

# remove extraneous "./"s from the path
$srcdir =~ s,/\./,/,g;

# remove extraneous ".."s from the path
while ($srcdir =~ s,/[^/]*/\.\.,,) {
}

# remove the final slash
$srcdir =~ s,(.*)/$,$1,;

if (!($install_dir)) {
    $install_dir = "${pwd}/install/";
}

print "pwd is $pwd\n";
print "srcdir is $srcdir\n";

###########################################################################
# Collect user input and set variables
###########################################################################

$vernum = `${srcdir}/tagtool -force -action=print -file=${srcdir}/version_num`;
chop $vernum;

###########################################################################
# Tell the user what we're going to do
###########################################################################

print "Run this script in the place where you want to build ${product}.\n\n";

print "Making build tree for ${product} version ${vernum}\n";
print "with sources in directory ${srcdir}\n\n";

###########################################################################
# Make a build directory tree that mirrors the src directory tree
###########################################################################

# find all the makefiles, and print just the paths that they are in.
# Then sort so that we will make sure to create parent dirs before
# their children
$findstring = "(find $srcdir -follow -path $srcdir/build -prune -or -path $srcdir/dist -prune -or -path $srcdir/old -prune -or -name Makefile.in -exec dirname {} \\; | sort) |";
print $findstring;
open(DIRLIST, $findstring);

while (<DIRLIST>) {
    chop;
    /$srcdir(.*)/;
    local $subdir = "$1";

    print "subdir is $subdir\n";

    mkdir "$pwd/$subdir", 0755;

    `sed -e "s,\@xtools_dir\@,$install_dir," -e "s,\@src_dir\@,${srcdir}${subdir}," < ${srcdir}$subdir/Makefile.in > ${pwd}${subdir}/Makefile`
}
