use ExtUtils::MakeMaker;
# use inc::Module::Install;
use IO::File;
use Config;
use Getopt::Std;

do "./lib/SIL/Shoe.pm";

getopts('e');

# $opt_e - disable inclusion of encrem.pl in exe

#$VERSION = "1.30";

$fversion = $SIL::Shoe::VERSION;
$fversion =~ s/\./_/og;

@scripts = grep {!m/\./o && !m/[~]$/o && -f } glob("Scripts/*");

# incantation to enable MY::pm_to_blib later on
if ($^O eq 'MSWin32')
{
    push(@ExtUtils::MakeMaker::Overridable, qw(pm_to_blib));
    @extras = (dist => { 'TO_UNIX' => 'perl -Mtounix -e "tounix(\"$(DISTVNAME)\")"' });
}

# we do this to avoid installing Make.pm
%pms = map { my ($v) = $_; $v =~ s/^lib/\$(INST_LIB)/o; $_ => $v; }
    (glob("lib/SIL/Shoe/*.pm"), glob("lib/SIL/*.pm"), glob("lib/SIL/Shoe/Backend/*.pm"),
     glob("lib/SIL/Shoe/Sort/*.pm"), glob("lib/Unicode/Collate/allkeys.txt"), glob("lib/Text/*.pm"));

$perlbin = $Config{'bin'};
$fhi = IO::File->new("< ShUtils.isb") || die "Can't find ShUtils.isb";
$fho = IO::File->new("> ShUtils.iss") || die "Can't find ShUtils.iss";

$fho->print(<<'EOT');
; Don't edit me, edit ShUtils.isb. I'm autogenerated from that file

EOT
while (<$fhi>)
{
    s/{perl:\s*(.*?)\s*}/$1/oigee;
    $fho->print($_);
}
$fhi->close;
$fho->close;
    
    
WriteMakefile (
        NAME => "SIL::Shoe",
        VERSION_FROM => "lib/SIL/Shoe.pm",
#        VERSION => $VERSION,
        EXE_FILES => \@scripts,
        AUTHOR => "martin_hosken\@sil.org",
        ABSTRACT => "Shoebox support utilities",
        PREREQ_PM => {
            'Algorithm::Diff' => 0,
            'Algorithm::Merge' => 0,
            'Archive::Zip' => 0,
            'Encode::Registry' => 0,
            'Encode::TECkit' => 0,
            'OpenOffice::OODoc' => 0,
            'Pod::Usage' => 0,
            'Unicode::Collate' => 0,
            'Image::Size' => 0,
            },
        PM => {%pms},
        @extras
    );

if ($^O eq 'MSWin32') {
# incantation to solve the problem of everyone's $Config{make} being 'nmake'
# when we want 'pmake'. And $Config{} is read only.
# actually, this is just a copy of the code from ExtUtiles::MM_Win32 tidied
# up (to expose tabs) and the dependency on Config removed
sub MY::pm_to_blib
{
    my $self = shift;
    my($autodir) = $self->catdir('$(INST_LIB)','auto');
    return <<"EOT";

pm_to_blib: \$(TO_INST_PM)
\t$self->{NOECHO}\$(PERL) \"-I\$(INST_ARCHLINE)\" \"-I\$(INST_LIB)\" \\
\t\"-I\$(PERL_ARCHLIB)\" \"-I\$(PERL_LIB)\" -MExtUtils::Install \\
\t-e \"pm_to_blib({ qw[\$(PM_TO_BLIB)] }, '$autodir')
\t$self->{NOECHO}\$(TOUCH) \$@

EOT
}

}

sub MY::postamble
{
    my (@files) = map {m|Scripts/(.*)$|oi; $1;} @scripts;
    my ($res, $fh, $files);
    
    $files = join (' ', map {m|Scripts/(.*)$|oi; "$1.bat"} @scripts);
    $files =~ s/addpath\.bat\s*//o;     # remove addpath since don't need a .bat
    $files .= " encrem.bat" unless $opt_e;
    $fh = IO::File->new("> addbats.pl") || die "Can't create addbats.pl";

    $fh->print(<<"EOT");
#! perl
foreach \$f (qw($files))
{
    if (\$ARGV[0] eq '-r')
    {
        unlink "\$ARGV[1]\\\\\$f";
    }
    else
    {
        my (\$pl) = \$f;
        \$pl =~ s/\\.bat//o;
        open(FH, "> \$ARGV[0]\\\\\$f") || die \$@;
        print FH "\@\\"\$ARGV[0]\\\\parl.exe\\" \\"\$ARGV[0]\\\\shutils.par\\" \$pl %1 %2 %3 %4 %5 %6 %7 %8 %9\\n";
        close(FH);
    }
}
EOT
    $fh->close();
    
    push (@scripts, "addbats.pl");
    push (@scripts, "$perlbin/encrem") unless $opt_e;

	if ($^O eq 'MSWin32')
	{
		require Win32::TieRegistry;
		Win32::TieRegistry->import (Delimiter=>"/") ;
		$compile = $Registry->{'Classes/InnoSetupScriptFile/shell/Compile/command//'};
		$compile =~ s/\s*"?%1"?.*$//;
		$compile = "start \"compile\" /wait $compile";
	}
    
    $res .= "exe : ShUtils_$fversion.exe\n\n";

    $res .= "ShUtils_$fversion.exe : Scripts\\shutils.par\n";
    $res .= "\t$compile ShUtils.iss\n\n";
    
    $res .= "Scripts\\shutils.par : ";
    $res .= join(' ', @scripts);
    $res .= "\n\tpp -B -p -o Scripts\\shutils.par -a lib\\Unicode\\Collate\\allkeys.txt -M SIL::Encode_all " . join(' ', @scripts);
    $res .= "\n\n";
    
    $res;
}
