#!/usr/bin/perl -w

# daemon-ctl 1.1, 2001/02/17 (dws)

use strict;

my $action = shift @ARGV;
my $name = shift @ARGV;
my @args = @ARGV;

my $PIDDIR='/var/run';
my $PIDFILE="$PIDDIR/$name.pid";

-d "$PIDDIR" || mkdir("$PIDDIR",755) || die "$0: can't mkdir $PIDDIR\n";

my $usage=1;
if($action eq 'stop' || $action eq 'restart') {
	print "stopping $name...";
	if(open(PID, "<$PIDFILE")) {
		my $pid=<PID>;
		chomp $pid;
		close(PID);
		kill("TERM", $pid);
		unlink "$PIDFILE" or warn "$0: can't remove $PIDFILE\n";
		print " ok.\n";
	}
	else {
		print " no pid.\n";
	};
	$usage=0;
}
if($action eq 'start' || $action eq 'restart') {
	print "starting $name...";
	if(! -x $args[0]) {
		print " $args[0] not found.\n";
	}
	else {
		my $pid=fork;
		if($pid) {
			open(PID, ">$PIDFILE") or die "$0: can't write to $PIDFILE\n";
			print PID "$pid\n";
			close(PID);
			print " ok.\n";
		}
		else {
			exec(@args) or die "$0: can't exec @args\n";
		}
	}
	$usage=0;
}
if($action eq 'getpid') {
	open(PID, "<$PIDFILE") or do {
		print "$0: can't open $PIDFILE\n";
		exit 1;
	};
	my $pid=<PID>;
	print "$pid";
	$usage=0;
}
if($usage) {
	print "usage: $0 {start|restart|stop|getpid}\n";
}

exit 0;

__END__

=head1 NAME

daemon-ctl - start/stop a program in the background

=head1 SYNOPSIS

daemon-ctl I<action> I<name> I<program> [I<args ...>]

=head1 DESCRIPTION

This program is a init-script helper. It starts/stops a program in the
background by using a file (in F</var/run>) to store the PID of the started
program.

I<action> can be one of:

=over 10

=item start

Start the program I<program> with it's arguments I<args> and store it's pid in
F</var/run/name.pid>.

=item stop

Stop the program by sending a TERM signal to the process written in
F</var/run/name.pid>.

=item restart

Do a stop and immediately a start.

=item getpid

Print the PID of the program.

=head1 EXAMPLE

 #!/bin/sh -e

 DAEMONCTL=/usr/drwho/vault/isgptp/bin/daemon-ctl
 GEDAFED=/usr/drwho/vault/isgptp/bin/gedafed

 test -f $DAEMONCTL || exit 0

 $DAEMONCTL $1 gedafed $GEDAFED

=head1 AUTHOR

David Schweikert <dws@ee.ethz.ch>
