#!/usr/bin/perl
#/*
# * make_make.pl
# *
# *
# *
#*/
# /*
# *
# * Copyright (C) 2005       Yoav Zach <yoav.zach@intel.com>
# * Copyright (C) 2005       Eric Lin <eric.lin@intel.com>
# * Copyright (C) 2005       Dror Shenkar <dror.shenkar@intel.com>
# *
# */
# /*
# * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# *
# * This library is free software; you can redistribute it and/or
# * modify it under the terms of GNU Lesser General Public
# * License as published by the Free Software Foundation
# * version 2.1 of the License.
# *
# * This library is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU Lesser General Public License for more details.
# *
# * You should have recieved a copy of the GNU Lesser General Public License
# * along with this library; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# * or view it at http://www.gnu.org/licenses/lgpl.html
# *
# * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# */

use Getopt::Std;
# read the options from the command line
$ret_val = getopts ("t:s:f:");
if ($ret_val != 1)
{
	die "Unknown options.\n";
}
if (($opt_t eq "") || (($opt_t ne "Makefile.rules") && ($opt_t ne "Makefile.list"))) {
	die 'Error! Usage: make_make.pl -t <Makefile.rules|Makefile.list> [-s <skipped files>] [-f <compilation flags>]';
} elsif ($opt_t eq "Makefile.rules") {
	$target = 'r';
} else {
	$target = 'l';
}
$skipped="\"$opt_s\"";
$flags=$opt_f;

$objs="OBJS:=";
$srcs="SRCS:=";
$hdrs="HDRS:=";
$rules="";
@dirs=`find . -maxdepth 1 -type d | grep -v bin.`;
foreach $d (@dirs) {
	chomp $d;
	@src=`find $d -maxdepth 1 -name "*.[cS]"`;
	foreach $f (@src) {
		if ($f=~m/\.\/(.*)\/(.*)$/) {
			$dir=$1;
			$file=$2;
		} elsif ($f=~m/\.\/(.*)$/) {
			$dir=".";
			$file=$1;
		} else {
			die "unexpected item '$f'";
		}
		$src="$dir/$file";

		$obj=$file;
		$obj=~s/\.[cS]/.o/;
		$srcs.="$src ";
		if ($skipped !~ $file) {
			$objs.="\$(BINDIR)/$obj ";
			$dep=`gcc $flags -MM $f`;
			$rules.="\$(BINDIR)/$dep";
			if ($file=~/\.c$/) {
				$rules.="\t\$(CC) \$(CFLAGS) -c -o \$@ \$<\n\n";
			} else {
				$rules.="\t\$(AS) \$(ASFLAGS) -c -o \$@ \$<\n\n";
			}
		}
	}
	@hdr=`find $d -name "*.h"`;
	foreach $h (@hdr) {
		chomp $h;
		$hdrs.="$h ";
	}
}


if ($target eq 'r') {
	print $rules;
} else {
	print "$hdrs\n";
	print "$srcs\n";
	print "$objs\n";
}

