#!perl -w

use strict;
use File::Find;


$ENV{SDL_PERL_RELEASE_ID} = "SDL_perl-1.20.win32";
$ENV{TAR}      = 'C:\cygwin\bin\tar.exe';
$ENV{GZIP}     = 'C:\cygwin\bin\gzip.exe';
$ENV{MAKENSIS} = '"c:\Program Files\NSIS\makensis.exe"';
$ENV{NSISCFG}  = 'sdlperl.nsi';
$ENV{NSISCFGENV} = $ENV{NSISCFG}. ".env";
$ENV{PPDFILE}    = "SDL_perl.ppd";
$ENV{MAKE}    = "nmake";
$ENV{PERL}    = "perl";
$ENV{RM}    = "del";



my $tarFile = $ENV{SDL_PERL_RELEASE_ID}. ".tar";
my $nsisCfg = $ENV{NSISCFG}; 
my $sdlDll  = $ENV{SDL_DLL_PATH}; 

my @foundDLLs = ();

my @ignoreDLLs = (
				  '.*\visualc\win32bin\SDL.dll$',
				  '.*\visualc\win32bin\sdl_sound_d.dll$',
				  );

scan_dll(FOUND_DLL => \@foundDLLs, 
		 IGNORE_DLL => \@ignoreDLLs);


system($ENV{MAKE}      , 'clean');
system($ENV{PERL}      , 'Makefile.PL');
system($ENV{MAKE});


system $ENV{RM},  $tarFile.".gz";
system $ENV{RM},  $ENV{PPDFILE};

system($ENV{TAR}       , 'cvf' , $tarFile, 'blib');
system($ENV{GZIP}      , '--best', '--force', $tarFile);

system($ENV{MAKE}      , 'ppd'); # "BINARY_LOCATION=$tarFile.gz");
envreplace_ppd();

envreplace_nsiscfg(DLLS => \@foundDLLs);

system($ENV{MAKENSIS}  , $nsisCfg);


exit;





sub envreplace_ppd
{
	local $/ = undef;
	open PPD,  "<$ENV{PPDFILE}" or die "$!";
	my $text = <PPD>;
	close PPD;

	$text =~ s/CODEBASE HREF=""/CODEBASE HREF="$ENV{SDL_PERL_RELEASE_ID}.tar.gz"/m;

	open PPD,  ">$ENV{PPDFILE}" or die "$!";
	print PPD $text;
	close PPD;
}



				
sub scan_dll
{
	my %args = ( @_
				);
	my $dll        = $args{FOUND_DLL};
	my $ignoreDlls = $args{IGNORE_DLL};
# find the SDL DLLS'

find( sub 
{
	my $fullPath=$File::Find::name;
	$fullPath =~ s/\//\\/g;
	if ($fullPath =~ /\.dll$/i)
	{
		my $foundIgnoreDll = 0 ;
		foreach my $regexOrg (@$ignoreDlls)
		{
			my $regex = $regexOrg;
			$regex =~ s/\\/\\\\/g;
			#print "********** checking against : $regex\n";
			$foundIgnoreDll = 1 if $fullPath =~/$regex/;
		}
		push @$dll, $fullPath if not $foundIgnoreDll;  
	}
	#print $fullPath."\n";
} , split ';', $sdlDll);

}


# perform env substitution on 
sub envreplace_nsiscfg
{
	my %args = ( @_
				);
	
	my @dll = @{$args{DLLS}};
open NSIS_IN,  "<$ENV{NSISCFGENV}" or die "$!";
open NSIS_OUT, ">$ENV{NSISCFG}"    or die "$!";

while (my $line = <NSIS_IN>)
{
	if ( $line =~ /\%LIST:DLLFiles\%/)
	{
		print ">>>> FILE REP\n";
		print NSIS_OUT map { "File \"$_\"\n"; } @dll;		
	}
	elsif ($line =~ /\%(.*)\%/)
	{
		print ">>>> ENV REPL $1\n";
		my $var = $ENV{$1} or die "No value set in ENV for variable named $1";
		$line =~ s/\%$1\%/$var/g;
		print NSIS_OUT $line;
	}
	else
	{
		print ">>>> WRITE\n";
		
		print NSIS_OUT $line;
	}
	print ">>>>>>>>>> ".$line;
}
close NSIS_IN;
close NSIS_OUT;


print ">" x 80 ."\n";
print "DLLS: \n", join "\n", @dll;
print "\n";
#print "<" x 80 ."\n";		

}
