#!/usr/bin/perl

# for i18n
use POSIX;
use Locale::gettext;

setlocale (LC_ALL, "");
textdomain ("urpmi");

sub _ {
    my ($format, @params) = @_;
    sprintf(Locale::gettext::gettext($format), @params);
}

$automatic = 0;
$timeout = 15;

$DIR = "/var/lib/urpmi";
$BASE = "$DIR/autoirpm";
$INSTALL_SCRIPT_REP = "$BASE.scripts";

$rpm = shift @ARGV;
print STDERR "autoirpm: ", _("installing %s\n",$rpm);

`xtest`;
$X = ($? == 0);

my $pid;
$SIG{ALRM} = sub { $pid and kill 9, $pid; not_found(); };
alarm $timeout;

if (!$automatic) {
    $interactive_mesg = _("Automatic installation of packages...\nYou requested installation of package %s\n",$rpm) . _("Is it OK?");
    if ($X) {
	my $ok = _("Ok");
	my $cancel = _("Cancel");
	($pid = fork) or exec "gmessage", "-default", $ok, "-buttons", "$ok:0,$cancel:2", $interactive_mesg;
	wait();
	$? and not_found();
    } else {
	if (isatty(0)) {
	    $noexpr = _("Nn");
	    $yesexpr = _("Yy");
	    print $interactive_mesg, _(" (Y/n) ");
	    <STDIN> =~ /[$yesexpr]/ or not_found();
	} else {
	    # Arghhh not in automatic and no way to contact the user... dying
	    not_found();
	}
    }
}
alarm 0;

$urpmi = !$automatic && $X ? "gurpmi" : "urpmi";
fork or exec $urpmi, "--comment", $ARGV[0], $rpm; wait;

# launch the initial prog
(readlink $ARGV[0]) !~ /$INSTALL_SCRIPT_REP/ and exec @ARGV;

not_found();

sub not_found {
    print STDERR _("%s: command not found\n",$rpm);
    exit 127;
}