#!/usr/bin/env perl

open( SRC_MAKEFILE , "<Makefile.template" )
	|| die "Can't open Makefile.template\n";

unlink( "Makefile" );

open( MAKEFILE , "+>Makefile" ) || die "Can't open Makefile\n";

@src_makefile = <SRC_MAKEFILE>;

@cdir = grep(/^\s*COMPILE_DIR\s*=\s*([^\s]+)\s*$/ , @src_makefile );

if ( $#cdir == 0 )
{
	$have_comp_dir = true;
	$comp_dir = "\$\(COMPILE_DIR\)";
	$comp_dir_str = "${comp_dir}/";
}
else
{
	$have_comp_dir = false;
	$comp_dir = "";
	$comp_dir_str = "";
}

@actions = ();

@files = <*.act>;
foreach( @files )
{
	/^(.*)\.act$/;

	push( @actions , $1 );
}


$ACT = "";
foreach( @actions )
{
	$ACT .= " \\\n\t${comp_dir_str}autogen_act_$_.o";
}



sub  get_dependency($)
{
	my ($action) = @_;
	my @depend_list;

	open( ACT_SRC , "<${action}.act" )
		|| die "$0: Can't open ${action}.act\n";

	while(<ACT_SRC>)
	{
		if ( /^\s*#\s*INCLUDE\s+(\w+)$/o )
		{
			push( @depend_list , $1 );
		}
		elsif ( /^\s*\%parent\s+:?\s*(\w+)$/o )
		{
			push( @depend_list , $1 );
		}
	}

	close( ACT_SRC );

	@depend_list;
}


$DEP = "";

# *.act -> autogen_act_*.h autogen_act_*.h *.cc
foreach( @actions )
{
	$DEP .= "${comp_dir_str}autogen_act_${_}.cc "
		. "${comp_dir_str}autogen_act_${_}.h: ${_}.act\n";
#	$DEP .= "${comp_dir_str}autogen_act_${_}.h: ${_}.act\n";

	if ( $have_comp_dir )
	{
		$DEP .= "\t\$(SRCGEN) -o ${comp_dir} ${_}.act\n";
	}
	else
	{
		$DEP .= "\t\$(SRCGEN) ${_}.act\n";
	}

	$DEP .= "\n";
}

# for actname.o dependency
foreach $act ( @actions )
{
	$DEP .= "\n";
	$DEP .= "${comp_dir_str}autogen_act_${act}.o: \\\n";
	$DEP .= "\t${comp_dir_str}autogen_act_${act}.h";
#	$DEP .= "\t${comp_dir_str}autogen_act_${act}.h \\\n";
#	$DEP .= "\t${comp_dir_str}autogen_act_${act}.cc";

	my @dep = get_dependency( $act );

	foreach $d ( @dep )
	{
		if ( -r "${d}.act" )
		{
			$DEP .= " \\\n";
			$DEP .= "\t${comp_dir_str}autogen_act_${d}.h";
		}
	}
	$DEP .= "\n";

	$DEP .= "\t\$(CXX) \$(CXXFLAGS) ${comp_dir_str}autogen_act_${act}.cc"
		. " -c -o ${comp_dir_str}autogen_act_${act}.o\n";
}

# for 'make autogen'
$DEP .= "\n";
$DEP .= "\n";
$DEP .= ".PHONY: autogen\n";
$DEP .= "\n";
$DEP .= "autogen:";
foreach( @actions )
{
#	$DEP .= " \\\n\t${comp_dir_str}autogen_act_${_}.cc "
#		."${comp_dir_str}autogen_act_${_}.h";
	$DEP .= " \\\n\t${comp_dir_str}autogen_act_${_}.cc";
}
$DEP .= "\n";


# for 'make act_actname'
$DEP .= "\n";
$DEP .= "\n";
foreach( @actions )
{
	$DEP .= "act_${_}: ${comp_dir_str}autogen_act_${_}.o\n";
}
$DEP .= "\n";
foreach( @actions )
{
	$DEP .= ".PHONY: act_${_}\n";
}


chomp( $DEP );


print MAKEFILE "#\n";
print MAKEFILE "# This file is automatically generated"
		. " from Makefile.template\n";
print MAKEFILE "#\n";
print MAKEFILE "\n";

foreach( @src_makefile )
{
	s/\@ACTIONS\@/${ACT}/go;
	s/\@DEPENDS\@\s*:?/${DEP}/go;

	print MAKEFILE;
}

close( MAKEFILE_ORG );
close( MAKEFILE );

chmod( 0444 , "Makefile" );
