#!/usr/bin/perl
#
# bootsplash2fbsplash -- theme conversion utility 
# (c) 2004-2005 Michal Januszewski <spock@gentoo.org>
#
# Usage: bootsplash2fbsplash [--remove-comments] <theme_name>
#

$path_bp = "/etc/bootsplash/";
$path_fbspl = "//etc/splash";
$comments = 1;
$theme = "";

sub usage
{
	print "bootsplash2fbsplash theme converter / splashutils-1.5.4.4\n";
	print '(c) 2004-2005 Michal Januszewski <spock@gentoo.org>'."\n\n";
	print "Usage: bootsplash2fbsplash [--remove-comments] <theme_name>\n";
}

my @args = @ARGV;

while ($arg = shift @args) {
	if ($arg eq "--remove-comments") {
		$comments = 0;
	} elsif ($arg eq "--bootsplash-path") {
		$path_bp = shift @args;
	} elsif ($arg eq "--fbsplash-path") {
		$path_fbspl = shift @args;
	} else {
		$theme = $arg;
	}
}

if ($#ARGV < 0 || $theme eq "") {
	usage();
	exit 0;
}

$path_bp =~ s#//#/#g;
$path_fbspl =~ s#//#/#g;

$cfgroot = "$path_bp/$theme/config";
$fbspl_images = "$path_fbspl/$theme/images";

opendir(DIR, "$cfgroot") || die "Can't open $cfgroot: $!"; 
@configs = grep { /\.cfg$/ && /bootsplash/ && -f "$cfgroot/$_" } readdir(DIR);
closedir(DIR);

foreach $cfg (@configs) {
	$cfg =~ /(\d+)x(\d+)/;
	$xres = $1;
	$yres = $2;

	`mkdir -p $fbspl_images`;
	
	open(IN, "<$cfgroot/$cfg");
	open(OUT, ">$path_fbspl/$theme/${xres}x${yres}.cfg");

	@known_keyw = ("bgcolor", "tx", "ty", "tw", "th", "text_x", "text_y",
		       "text_size", "text_color");
	$empty = 0;
	       
	while ($line = <IN>) {

		if ($line =~ /^\s*#/ || $line =~ /^\s*$/ || $line =~ /^\s*box /) {
			goto ok;
		} elsif ($line =~ /(silent)?jpeg=(.*)$/) {
		
			$empty = 0;
			
			if ($1 eq "silent") {
				$t = "silent";
			} else {
				$t = "verbose";
			}
			
			$t = "$fbspl_images/$t-${xres}x${yres}.jpg";
			$line = "$1pic=$t\n";
		
			if (-e "$2") { 
				`cp -fp -H "$2" "$t"`;
			} else {
				print "Error: $2 not found!\n"
			}
		} else {
			foreach $key (@known_keyw) {
				if ($line =~ /^\s*$key=/) {
					$empty = 0;
					goto ok; 
				}
			}
			next;
		}

ok:		if (!$comments) {
			if ($line =~ /^\s*#/) {
				next;
			} elsif ($line =~ /^\s*$/) {
				if (!$empty) {
					$empty = 1;
				} else {
					next;
				}
			}
		}
		
		print OUT $line;
	}

	$a = `md5sum "$fbspl_images/silent-${xres}x${yres}.jpg" 2>/dev/null | cut -f1 -d' '`;
	$b = `md5sum "$fbspl_images/verbose-${xres}x${yres}.jpg" 2>/dev/null | cut -f1 -d' '`;

	chomp $a;
	chomp $b;
	
	if ($a eq $b) {
		`rm -f "$fbspl_images/silent-${xres}x${yres}.jpg"`;
		`ln -s "$fbspl_images/verbose-${xres}x${yres}.jpg" "$fbspl_images/silent-${xres}x${yres}.jpg"`;
	}

	close(OUT);
	close(IN);
	
	print "o Parsed $cfg (${xres}x${yres})\n";
}

