#!/usr/local/bin/perl5 -s
#
# This file is part of SnarfNews
# Copyright (C) 1991,1992,1993,1994,1995,1996 Alec Muffett
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

sub TrapALRM
{
    $debug && warn "$0: parent: timer expired: @ARGV\n";

    if ($cpid)
    {
	$debug && warn "$0: parent: killing $cpid\n";

	kill(15, -$cpid);
	sleep(5);
	kill(15, $cpid);
	sleep(5);
	kill(9, -$cpid);
	kill(9, $cpid);
    }

    exit(1);
}

$_ = shift;

unless (/^(\d+)(h|m|s)?$/oi)
{
    die "Usage: $0 N[h|m|s] command args ...\n";
}

$kill_after = $1;
$kill_after *= 60 if (($2 eq "m") || ($2 eq "M"));
$kill_after *= 3600 if (($2 eq "h") || ($2 eq "H"));

$debug && warn "$0: parent: timeout is $kill_after seconds\n";

$cpid = 0;

if ($cpid = fork)               # happy parent
{
    $debug && warn "$0: fork: created child, pid=$cpid\n";
}
elsif (defined($cpid))          # happy child
{
    $debug && warn "$0: child: exec(@ARGV)\n";
    exec(@ARGV) || die "$0: child: exec failed: $!\n";
    $debug && warn "$0: child: THIS CANT HAPPEN\n";
}
else                            # population explosion
{
    $debug && warn "$0: fork: error: $!\n";
}

$debug && warn "$0: parent: starting timer\n";

$SIG{"ALRM"} = "TrapALRM";        # set the egg-timer
alarm($kill_after);             # start it
waitpid($cpid, 0);              # wait to see what happens
$debug && warn "$0: parent: child exited status=$?\n";
exit($? ? 1 : 0);               # and return a status code
