#!/usr/local/bin/perl
# mkmf: Munge Makefile.source into Makefile with System targets set up
#
# Portions of this software are Copyright 1995 by Randall Atkinson and Dan   
# McDonald, All Rights Reserved. All Rights under this copyright are assigned   
# to the U.S. Naval Research Laboratory (NRL). The NRL Copyright Notice and   
# License Agreement applies to this software.   
#
#	History:
#
#       Modified at NRL for OPIE 2.01. Added A/UX target.
#	Written at NRL for OPIE 2.0.
#
@targets = ( "Solaris", "SunOS", "4.4BSD", "BSD/OS", "Linux", "IRIX", "HP-UX9",
		"HP-UX10", "AIX", "FreeBSD", "NetBSD", "A/UX" );

open(MAKEFILE, ">Makefile");
print MAKEFILE "#!/usr/bin/make\n#\n# This Makefile is a product of Makefile.source being run through the mkmf\n# Perl script to generate all of the System-Target format make targets\n# automatically and is ready to be hacked to suit your needs. If you make\n# modifications to the OPIE Makefiles as a programmer, please modify the\n# Makefile.source file instead of this one.\n#\n##\n";

$copyit = 1;
open(MAKEFILE_SOURCE, "<Makefile.source");
while(<MAKEFILE_SOURCE>) {
	/^#!\/usr\/bin\/make/ && do {
		$copyit = 0;
	};
	/^##/ && do {
		$copyit = 1;
	};
	/^# Chop, Chop/ && do {
		$copyit = 0;
	};
	if ($copyit && !/##/) {
		print MAKEFILE $_;
	};
};
close(MAKEFILE_SOURCE);

print "Building Makefile. Targets:\n\n";

foreach $i (@targets) {
	$target = $i;
	$target =~ s:\/::g;
	$target =~ s:\-::g;
	$target =~ s:\.::g;
	$target =~ tr/[A-Z]/[a-z]/;
	print "$i $target\n";

	$pluck = 0;
	@targetvars = ();
	open(MAKEFILE_SOURCE, "<Makefile.source");
	while (<MAKEFILE_SOURCE>) {
		if ($pluck) {
			chop($_);
			/^#([A-Z_]+)=([A-Za-z0-9\-_\ :\/=\.]+)$/ && do {
				@targetvars = (@targetvars, "$1=\"$2\"");
			};
			$pluck = 0;
		} else {
			/^# / && do {
				/$i/ && do {
					$pluck = 1;
				};
			};
		};
	};
	close(MAKEFILE_SOURCE);
	print MAKEFILE "\n$target: $target-all\n";
	print MAKEFILE "\n$target-: $target-all\n";
	foreach $k ("all", "test", "install", "uninstall") {
		print MAKEFILE "\n";
		print MAKEFILE "$target-$k:\n\tmake";
		foreach $j (@targetvars) {
			print MAKEFILE " $j";
		};
		print MAKEFILE " $k\n\n";
		close(MAKEFILE_SOURCE);
	};
};
