#!/usr/bin/perl
# This program is copyright 2002 by Joey Hess <joeyh@debian.org>,
# and is licensed under the terms of the GNU GPL, version 2 or higher.

sub daemonize {
	$pid=fork;
	if ($pid == 0) {
		$pid=fork;
		if ($pid == 0) {
			foreach my $sig ($SIG{TSTP}, $SIG{TTIN}, $SIG{TTOU}, $SIG{HUP}, $SIG{PIPE}) {
				$sig = 'IGNORE';
			}
			close STDOUT;  open STDOUT, "+>/dev/null";
			close STDIN;   open STDIN, "+>/dev/null";
			close STDERR;  open STDERR, "+>/dev/null";
			exec @_;
			exit 1;
		} else {
			$SIG{CHLD} = 'IGNORE';
			exit 0;
		}
	} else {
		$SIG{CHLD} = 'IGNORE';
		exit 0;
	}
}

my $url=shift;
if (exists $ENV{BROWSER}) {
	foreach (split ':' , $ENV{BROWSER}) {
		if (! /%s/) {
			$_.=" %s";
		}
		# substitute %s with url, and %% to %.
		s/%([%s])/$1 eq '%' ? '%' : $url/eg;
		$ret=system split ' ', $_;
		if ($ret >> 8 == 0) {
			exit(0);
		}
		# on failure, continue to next in list
	}

	print STDERR "None of the browsers in \$BROWSER worked!\n";
	exit 1;
}

if (exists $ENV{DISPLAY}) {
	if (-e '/usr/bin/x-www-browser') {
		daemonize('/usr/bin/x-www-browser', $url);
	}
	elsif (-e '/usr/bin/x-terminal-emulator' && -e '/usr/bin/www-browser') {
		daemonize("x-terminal-emulator", "-e", "/usr/bin/www-browser", $url);
	}
}
elsif (-e '/usr/bin/www-browser') {
	daemonize('/usr/bin/www-browser', $url);
}

print STDERR "Couldn't find a suitable web browser!\n";
print STDERR "Set the BROWSER environment variable to your desired browser.\n";
exit 1;
