#!/usr/bin/env perl

use strict;

our $modules;
our $dsl;
BEGIN
{ 
 select STDIN;
 $| = 1;
 select STDOUT;
	$| = 1;
	$modules = __FILE__;
	$modules = '.' if ($modules !~ /\//);
	$modules =~ s/\/[^\/]*$//gos;
	eval "use lib qw($modules/.);";
}
use lib qw(.);
use localization::localization;

my $esc = ' &"\'';

print "\n";
if (scalar(@ARGV) != 1 && scalar(@ARGV) != 2 && scalar(@ARGV) != 3)
{
	my $verPath = $0; 
	$verPath =~ s/\/[^\/]*$//gos;
	$verPath .= '/version';
	$verPath =~ s/([$esc])/\\$1/gos;
	my $ver = `cat $verPath`;
	$ver =~ s/\s+$//gos;

	print _L("(c) 2006, MiF, DSL batch processor version %#\n",$ver);
	print _L("usage in current directory: %# <dstDIR> [mp3/wav] [clean]\n\n",$0);
	print _L("mp3 flag used for converting all DSL WAV refs to MP3, you must convert WAVs to MP3s manually (wav is default)\n");
	print _L("check wav2mp3.pl utility from DictBuilder core\n\n");
	print _L("clean flag used for preserve disk free space\n\n");
	print _L("example: %# . mp3\n\n",$0);
	exit(1);
}

my $dst = $ARGV[0];

my $mp3 = $ARGV[1];
$mp3 ||= 0;
$mp3 = ($mp3 =~ /^mp3$/i) ? 1 : 0;

my $clean = $ARGV[2];
$clean ||= 0;
$clean = ($clean =~ /^clean$/i) ? 1 : 0;

print _L("Activated wav to mp3 filter\n") if ($mp3);
print _L("Dst directory: %#\n",$dst);
if (! -d $dst)
{
	print _L("Destination directory doesn't exists\n");
	exit(2);
}

my $scriptPath = $0;
$scriptPath =~ s/\/[^\/]*$//gos;

my $dslparser = $scriptPath .'/dslparser.pl';
my $packdict = $scriptPath .'/packdict.pl';

if (! -f $dslparser || ! -f $packdict)
{
	print _L("%# or %# utilities not found\n",$dslparser,$packdict);
	exit(3);
}

print _L("dslparser script: %#\n",$dslparser);
print _L("packdict script: %#\n",$packdict);
$dslparser =~ s/([$esc])/\\$1/gos;
$packdict =~ s/([$esc])/\\$1/gos;

system("rm -f *.dslc");
my @scontent = glob "*.[Dd][Ss][Ll]";
print _L("\nConverting DSLs: ");
foreach my $sc (@scontent)
{
	print "$sc ";
}
print "\n";

my $dslfile;

if (-d "$dst/all.mdict")
{
	print _L("all.mdict already exists at destination directory... Remove now [N/yes]? ");
	my $answer = <STDIN>;
	$answer =~ s/\s+$//gos;
	if ($answer !~ /^yes$/i)
	{
	 print _L("User canceled (you must type YES to continue)...\n");
	 exit(5);
	}
}

$dst =~ s/([$esc])/\\$1/gos;
system("rm -rf $dst/all.mdict 2>/dev/null; mkdir -p $dst/all.mdict");

my @dicts;
my $curdict;
my $cnt = 0;
my $len = scalar(@scontent);
foreach $dslfile (@scontent)
{
	$cnt++;
	print _L("Parsing DSL file [%# from %#]: %#\n",$cnt,$len,$dslfile);
	if (! -f $dslfile)
	{
		print _L("Can't found file %#\n",$dslfile);
		exit(4);
	}
	$dslfile =~ s/([$esc])/\\$1/gos;
	if ($mp3)
	{
		my $rc1 = "${dslfile}c1";
		
		my $enctest = `head -10 $dslfile`;
	 my $encoding = 'utf-16';
		$encoding = 'cp1251' if ($enctest =~ /#SOURCE_CODE_PAGE\s+"Cyrillic"/i);

		if (system("iconv -f $encoding -t utf-8 $dslfile > $rc1"))
		{
			print _L("Failed: Can't convert %# from %# to utf-8\n",$dslfile,$encoding);
			next;
		}
		$rc1 =~ s/\\([$esc])/$1/gos;
		my $rc2 = $rc1;
		$rc2 =~ s/1$//gos;
		local * M;
		local * O;
		my $ok = 1;
		open (M,"<$rc1") or $ok = 0;
		unless ($ok)
		{
			print _L("Can't open %# for reading\n",$rc1);
			exit(14);
		}
		open (O,">$rc2") or $ok = 0;
		unless ($ok)
		{
			print _L("Can't open %# for writting\n",$rc2);
			exit(15);
		}
		foreach my $ln (<M>)
		{
			$ln =~ s/\[s\](.+?)\.wav\[\/s\]/[s]$1.mp3[\/s]/gosi;
			print O $ln;
		}
		close(M);
		close(O);
		$rc1 =~ s/([$esc])/\\$1/gos;
		system("rm -f $rc1");
	}
	if (system("$dslparser $dslfile $dst silent"))
	{
		print _L("Warning: DSL parsing failed for %#...",$dslfile);
		next;
	}
	$curdict = $dslfile;
	$curdict =~ s/.dsl$//sio;
	$curdict =~ s/^.*\///gos;
	system("$packdict $dst/$curdict $dst silent");
	if ($clean)
	{
		system("mv $dst/$curdict.dict $dst/all.mdict");
		system("mv $dst/$curdict.idx $dst/all.mdict");
		system("mv $dst/$curdict.ext $dst/all.mdict");
	}
	else
	{
		system("cp $dst/$curdict.dict $dst/all.mdict");
		system("cp $dst/$curdict.idx $dst/all.mdict");
		system("cp -r $dst/$curdict.ext $dst/all.mdict");
	}
	if ($clean)
	{
		print _L("Cleaning...\n");
		system("rm -rf $dst/$curdict");
	}
	$curdict =~ s/\\([$esc])/$1/gos;
	$curdict =~ s/&/&amp;/gos;
	$curdict =~ s/</&lt;/gos;
	$curdict =~ s/>/&gt;/gos;
	push @dicts, $curdict;
}

print _L("\nWriting mdict.plist\n");
local * F;
$dst =~ s/\\([$esc])/$1/gos;
my $ok = 1;
open(F,">$dst/all.mdict/mdict.plist") or $ok = 0;
unless ($ok)
{
	print _L("Can't open mdict.plist for writting\n");
	exit(12);
}
print F <<EOF;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>aliases</key>
 <dict>
EOF
foreach $curdict (@dicts)
{
	print F "<key>$curdict</key><string>$curdict</string>\n";
}

print F <<EOF;
 </dict>

 <key>types</key>
 <dict>
EOF
foreach $curdict (@dicts)
{
	print F "<key>$curdict</key><string>Dec/PHT</string>\n";
}
print F <<EOF;
 </dict>

 <key>information</key>
 <dict>
EOF
foreach $curdict (@dicts)
{
	print F "<key>$curdict</key><string>$curdict</string>\n";
}
print F <<EOF;
 </dict>

	<key>groups</key>
	<dict>
		<key>Untitled Group</key>
		<array>
EOF
foreach $curdict (@dicts)
{
	print F "<string>$curdict</string>\n";
}
print F <<EOF;
		</array>
	</dict>

</dict>
</plist>
EOF

close(F);

system("rm -f *.dslc");
print _L("\nPlease edit all.mdict/mdict.plist before distibuting!\n");
print _L("Done\n");
