#!/usr/local/bin/perl

open( SRC_MAKEFILE , "<Makefile.org" ) || die "Can't open Makefile.org\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 = 1;
	$comp_dir = "\$\(COMPILE_DIR\)";
	$comp_dir_str = "${comp_dir}/";
}
else
{
	$have_comp_dir = 0;
	$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 );
		}
	}

	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";
	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 \\\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 .= "autogen:";
foreach( @actions )
{
	$DEP .= " \\\n\t${comp_dir_str}autogen_act_${_}.cc "
		."${comp_dir_str}autogen_act_${_}.h";
}
$DEP .= "\n";

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

chomp( $DEP );


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

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

	print MAKEFILE;
}

close( MAKEFILE_ORG );
close( MAKEFILE );

chmod( 0444 , "Makefile" );
