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

$path_bp = "/etc/bootsplash/";
$path_fbspl = "/etc/splash/";

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

if ($#ARGV < 0 || $#ARGV == 0 && $ARGV[0] eq "--remove-comments") {
	usage();
	exit 0;
}

if ($ARGV[0] eq "--remove-comments") {
	$theme = $ARGV[1];
	$comments = 0;
} else {
	$theme = $ARGV[0];
	$comments = 1;
}
$cfgroot = "$path_bp/$theme/config";
$fbspl_images = "$path_fbspl/$theme/images";

opendir(DIR, "$cfgroot") || die "Can't open $cfgroot: $!"; 
@configs = grep { /\.cfg$/ && -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";
			
			`cp -fp -H "$2" "$t"`;
		} 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" | cut -f1 -d' '`;
	$b = `md5sum "$fbspl_images/verbose-${xres}x${yres}.jpg" | cut -f1 -d' '`;
	
	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";
}

