#!/usr/bin/perl -w
#
# Version 1.0
#
# Copyright 2001 Jeff Garzik <jgarzik@mandrakesoft.com>
# Copyright 2002 Juan Quintela <quintela@mandrakesoft.com>
#
# This software may be used and distributed according to the terms
# of the GNU General Public License, incorporated herein by reference.
#
#
# Run "mkbuild.pl"
#
# This program generates the following files
#	Makefile
#	Makefile.drivers
#	Config.in
# using the information in the subdirs of this directory.
#
# subdirs need to have:
# 	a Config.in file
#	a Makefile with a O_TARGET/L_TARGET targets
#	The config.in should set a CONFIG_<module_dir_name> to m/y.

use strict;

opendir(THISDIR, ".");
# get dirs without . and .. garbage
my (@modules) = grep(!/\.\.?$/,grep(-d, readdir(THISDIR)));
closedir(THISDIR);

generate_config_in(@modules);
generate_makefile(@modules);
exit(0);

##########################################################################

sub generate_makefile {
    my (@modules) = @_;

    local *F;
    open F, "> Makefile" or die "Cannot create new Makefile: $!\n";
    print F <<'EOM';
#
# THIS IS AN AUTOMATICALLY GENERATED FILE.  DO NOT EDIT.
#

EOM
	
#    print F "mod-subdirs := ", join(" ", @modules), "\n\n" if @modules;
    printf F "obj-\$(%s) += %s/\n", to_CONFIG($_), $_ foreach @modules;
#    print F "\ninclude \$(TOPDIR)/Rules.make\n\n"
}



sub generate_config_in {
    my (@modules) = @_;

    local *F;
    open F, "> Kconfig" or die "Cannot create Kconfig: $!\n";
    print F <<"EOM";
#
# THIS IS AN AUTOMATICALLY GENERATED FILE.  DO NOT EDIT.
#

#menu_option next_comment
menu 'Unofficial 3rd party kernel additions'

EOM
	
    foreach (@modules) {
	die "No Kconfig in $_.\n" if ! -r "$_/Kconfig";
	print F "source 3rdparty/$_/Kconfig\n";
    }
    print F "\n#what a hack";
    print F "\nconfig 3RDPARTY";
    print F "\n\tbool\n\tdefault no";
    print F "\n\nendmenu\n";
}

sub to_CONFIG {
    local $_ = $_[0];
    tr/a-z/A-Z/;
    s/[\-\. ]/_/g;
    "CONFIG_$_";
}

sub find_target {
	my ($module_dir) = @_;

	local *F;
	open(F, "$module_dir/Makefile") or die "$module_dir/Makefile: $!\n";
	while (<F>) {
		chomp;
		return $1 if (/[LO]_TARGET.*:=\s+(\S+)/);
	}
}


