#!/usr/bin/perl

use strict;
use Getopt::Long;

my ($new, $url, $pid, $browser, $remote, $netscape, $mozilla, $verbose);

GetOptions('new' => \$new,
           'netscape' => \$netscape,
           'mozilla'  => \$mozilla,
           'verbose'  => \$verbose,
           'v'        => \$verbose);

$browser = $mozilla ? 'mozilla' : 'netscape';
$browser = $netscape ? 'netscape' : $browser;

my $procs = `ps x`;
my $got = $1 if ($procs =~ /($browser\/$browser)/);
$remote = ($got ? 1 : 0);
sleep (1) if ($remote);

FORK: {
          if ($pid = fork)
          {
              # parent
              exit 0;
          }
          elsif (defined $pid)
          {
              # child
              foreach $_ (@ARGV)
              {
                  $_ = sprintf("http://%s", $_) unless (/:\/\//);
                  my $cmd = &buildcmd($_);
                  print "MOZILLA COMMAND: $cmd\n" if ($verbose);
                  system($cmd);
                  sleep ($remote ? 1 : 5);
                  $remote = "-remote";
                  $new = 1;
              }
              exit 0;
          }
          elsif ($! =~ /No more process/)
          {
              # EAGAIN
              sleep 5;
              redo FORK;
          }
          else
          {
              die "Unable to fork subprocess: $!\n";
          }
      } # FORK

exit 0;


sub buildcmd
{
    my ($url) = @_;
    my $cmd;

#    $url =~ s/&/\\&/g;

    if ($remote)
    {
        $cmd = sprintf ("nice -5 %s -remote 'openURL(%s%s)' >/dev/null 2>/dev/null",
                        $browser,
                        $url, 
                        ($remote ? sprintf (', %s', ($mozilla ? 'new-window' : 'newWindow')) : ""));
    }
    else
    {
        $url =~ s/\&/\\\&/g;
        $cmd = sprintf ("nice -5 %s %s %s >/dev/null 2>/dev/null %s",
                        $browser,
                        ($browser eq 'netscape' ? '-no-about-splash' : ""),
                        $url,
                        '&');
    }

    return ($cmd);
}

