#!/usr/bin/perl

# Scans for cartridge images and writes a global or local debian menu file
# for stella then calls update-menus

my $DEBUG=($1 || 1) if($ARGV[0]=~m/^-d(\d*)$/);
my $MD5='/usr/bin/md5sum';

my $USER=$>;
my $STHOME=(getpwuid($USER))[7]."/.stella";

my @ROMPATHS=qw(/usr/lib/games/stella/roms);
push(@ROMPATHS, $STHOME."/roms") if($USER and -d $STHOME."/roms");

# First build the list of ROMs known to stella
my(%sums,$sum)=();
print "Scanning built-in ROM list\n" if($DEBUG);
open(PRO, "stella -listrominfo |");
while(<PRO>) {
    if (m/^([0-9a-f]+)\|([^\|]+)\|.*$/) {
	$sums{$1} = $2;
    }
}
close(PRO);

# Add any user-defined games
my $PRO="$STHOME/stella.pro";
if($USER and -e $PRO) {
    print "Using properties file: $PRO\n" if($DEBUG);
    open(PRO, $PRO);
    while(<PRO>) {
	$sum=$1 if(m/^"Cartridge\.MD5"\s+"(.*)"\s*$/);
	next if(!m/^"Cartridge\.Name"\s+"(.*)"\s*$/);
	next if(!length $sum);
	$sums{$sum}=$1;
	$sum='';
    }
    close(PRO);
}

my(%ents)=();
foreach $path (@ROMPATHS) {
    print "Scanning $path for ROM images.\n" if($DEBUG);
    chdir $path;
    opendir(DIR, ".");
    foreach $dent (readdir DIR) {
	next if($dent!~m/\.bin$/i);
	open(SUM, "-|") or exec($MD5, $dent);
	$sum=<SUM>;
	$sum=~s/ .*//s;
	close(SUM);
	my($name)=($sums{$sum});
	if(length $name) {
	    print "Found $name\n" if($DEBUG > 1);
	    $ents{$name}=sprintf(<<MENU, $name, "$path/$dent");
?package(stella):needs=x11 \\
                 section="Games/Arcade/Stella" \\
		 title="%s" \\
		 command="/usr/bin/stella %s"
MENU
	}
    }
    closedir(DIR);
}

my $MENU=(getpwuid($USER))[7]."/.menu/stella";
$MENU="/usr/lib/menu/stella" if(!$USER);

print "Writing out new $MENU\n" if($DEBUG);
umask 022;
open(OUT, ">$MENU");
print OUT $ents{$_} foreach(sort(keys %ents));
close(OUT);

exec('/usr/bin/update-menus');
