#!/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 $PRO="$STHOME/stella.pro";
$PRO="/etc/stella.pro" if(!$USER or ! -e $PRO); 

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

my(%sums,$sum)=();
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/games/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');
