#!/usr/bin/perl

# Author: William Lott
# rcs-header: $Header: /home/cvsroot/gd/src/tools/shared-misc/mk-build-tree.in,v 1.5 2002/02/26 21:03:48 brent Exp $

# Usage:
#
#     mk-build-tree [-pplatforms.descr]
#
# This program looks at your Defaults file, creates any directories
# that need to go in a build dir, and runs gen-makefile on every
# subdir.

$platforms_dot_descr = 0;
if ($#ARGV == 0 && $ARGV[0] =~ /-p.*/) {
    $platforms_dot_descr = shift(@ARGV);
}
if (@ARGV) { die("usage: $0 [-pplatforms.descr]\n") }

(-e 'Defaults') || die("No Defaults file.\n");

do "./Defaults";
die("Problem loading Defaults:\n  $@\n") if $@;

if ($buildroot) {
    $root_inode = (stat($buildroot))[1];
    $dot_inode = (stat('.'))[1];
    unless ($root_inode == $dot_inode) {
	die("Defaults set \$buildroot to:\n  $buildroot\nbut that is not the same as the current directory.\n");
    }
}

# Drive letters are considered optional, in no small part because we
# don't know whether we're running on a win32 or a Unix box.
# gen-makefile may have an opinion on the issue, though.
($srcroot =~ /^(\w:)|\//) || die("\$srcroot is not absolute:\n  $srcroot\n");

do mk_build_tree($srcroot, '.');

sub mk_build_tree {
    local ($srcdir, $builddir) = @_;

    $srcdir =~ s/^\.\///;
    $builddir =~ s/^\.\///;

    (-d $srcdir) || die("$srcdir is not a directory.\n");
    opendir(SRCDIR, $srcdir) || die("Can't open $srcdir: $!\n");

    unless (-d $builddir) {
	(-e $builddir)
	    && die("$builddir already exists and isn't a directory.");
	print "Making $builddir\n";
	mkdir($builddir, 0777) || die("mkdir($builddir) failed: $!\n");
    }

    local (@subdirs) = ();
    $has_makegen = 0;

    while ($entry = readdir(SRCDIR)) {
	if ($entry eq '.' || $entry eq '..' || $entry eq 'CVS') {
	}
	elsif ($entry eq "Makegen") {
	    $has_makegen = 1;
	}
	else {
	    $subdir = $srcdir . '/' . $entry;

	    if (-d $subdir && ! -l $subdir) {
		push(@subdirs, $entry);
	    }
	}
    }

    closedir(SRCDIR);
    
    if ($has_makegen) {
	print "Generating makefile for $builddir\n";
	($platforms_dot_descr 
	       ? system("perl", $buildroot.'/gen-makefile', $platforms_dot_descr, $builddir) 
               : system("perl", $buildroot.'/gen-makefile', $builddir))
	    && die("gen-makefile $builddir failed.\n");
    }

    foreach $subdir (@subdirs) {
	do mk_build_tree($srcdir.'/'.$subdir, $builddir.'/'.$subdir);
    }
}
