#!/usr/bin/perl -w
#
# Create the launcher scripts according to MIME-types for rox

# only run as root
exit(0) if $>;

my %hash = ();
my %prio = ();

while (<STDIN>) {
  chomp($_);
  if (/.*mimetypes="([^"]+)"\s+.*/ ) {
    my $mimetypes = $1;
    if (/.*command="([^"]+)"\s+.*/ ) {
      my $command = $1;

      next if ($command =~ /%/);

      my $priority = 0;

      if (/.*InitialPreference=([0-9]+)/ ) {
	$priority = $1;
      }
      foreach my $m (split(",|;", $mimetypes)) {
	my $cmd = $hash{$m};
	my $pri = $prio{$m};

	if ((!$cmd) || ($pri < $priority)) {
	  $hash{$m} = $command;
	  $prio{$m} = $priority;
	}
      }
    }
  }
}

system("rm -f /usr/share/Choices/MIME-types/*");

foreach my $m (sort keys %hash) {
  my $cmd = $hash{$m};
  my $pri = $prio{$m};
  $m =~ s@/@_@;

  open(MAILCAP, ">/usr/share/Choices/MIME-types/$m");
  print MAILCAP "#!/bin/sh\nexec $cmd \"\$@\"\n";
  close(MAILCAP);
  system("chmod 755 /usr/share/Choices/MIME-types/$m");
}
