#!/usr/bin/perl

my $version = "1.29";

use warnings;
use strict;
use File::Copy;
use File::Find;
use File::Path;
use Archive::Zip qw( :ERROR_CODES );

# cleanup
unlink <*.wgz>;
unlink <*.zip>;
rmtree("ComingNextB");
rmtree("ComingNextC");

# update version info
sed("comingNext/index.html", 'var version = \"(.*?)\";', 'var version = \"'.$version.'\";');
sed("comingNext/Info.plist", '<key>DisplayName<\/key>(\s*?)<string>Coming Next (.*?)<\/string>', '<key>DisplayName<\/key>$1<string>Coming Next '.$version.'<\/string>');
sed("comingNext/Info.plist", '<key>Version<\/key>(\s*?)<string>(.*?)<\/string>', '<key>Version<\/key>$1<string>'.$version.'<\/string>');

# add additional widget
copyrecursive("comingNext", "comingNextB");
sed("comingNextB/index.html", 'var panelNum = 0;', 'var panelNum = 1;');
sed("comingNextB/Info.plist", '<key>DisplayName<\/key>(\s*?)<string>Coming Next (.*?)<\/string>', '<key>DisplayName<\/key>$1<string>Coming Next B $2<\/string>');
sed("comingNextB/Info.plist", '<key>Identifier<\/key>(\s*?)<string>(.*?)<\/string>', '<key>Identifier<\/key>$1<string>$2b<\/string>');

# add additional widget
copyrecursive("comingNext", "comingNextC");
sed("comingNextC/index.html", 'var panelNum = 0;', 'var panelNum = 2;');
sed("comingNextC/Info.plist", '<key>DisplayName<\/key>(\s*?)<string>Coming Next (.*?)<\/string>', '<key>DisplayName<\/key>$1<string>Coming Next C $2<\/string>');
sed("comingNextC/Info.plist", '<key>Identifier<\/key>(\s*?)<string>(.*?)<\/string>', '<key>Identifier<\/key>$1<string>$2c<\/string>');

# package release
my $zip = Archive::Zip->new();
$zip->addTree("ComingNext", "ComingNext");
$zip->writeToFileNamed("comingNext.wgz");

$zip = Archive::Zip->new();
$zip->addTree("ComingNextB", "ComingNextB");
$zip->writeToFileNamed("comingNextB.wgz");

$zip = Archive::Zip->new();
$zip->addTree("ComingNextC", "ComingNextC");
$zip->writeToFileNamed("comingNextC.wgz");

$zip = Archive::Zip->new();
$zip->addFile("comingNext.wgz");
$zip->addFile("comingNextB.wgz");
$zip->addFile("comingNextC.wgz");
$zip->addFile("Readme.txt");
$zip->addFile("License.txt");
$zip->addFile("ComingNext_SkinFetcher_v1.3.sisx");
$zip->writeToFileNamed("comingNext_v$version.zip");

#########################################

my $copy_source;
my $copy_target;
sub copyrecursive {
	my ($source, $target) = @_;
	$copy_source = $source;
	$copy_target = $target;
	find({ wanted => \&copy_files, follow => 1, no_chdir => 1 }, $copy_source );
}
sub copy_files {
	my $targetdir = $File::Find::dir;
	$targetdir =~ s/^$copy_source/$copy_target/o;
	mkpath( $targetdir ) if not -e $targetdir;
	my $targetfile = $File::Find::name;
	$targetfile =~ s/^$copy_source/$copy_target/o;
	copy($File::Find::name, $targetfile);
}

#########################################

sub sed {
	my ($filename, $search, $replace) = @_;
	system("perl -p -i.bak -e \"s/$search/$replace/;\" $filename");
	unlink <$filename.bak>;
}