package daemons;

use warnings;
use strict;

use File::Slurp;
use Data::Dump qw/dump/;

use x11;

our $pids;
$pids = { httpd => $$ } unless defined $pids; # keep pids on refresh

sub DESTROY {
	warn "pids ",dump( $pids );
	foreach ( values %$pids ) {
		warn "kill $_";
		kill 1,$_ || kill 9, $_;
	}
}

$SIG{CHLD} = 'IGNORE';

sub start_stop {
	my $daemon = shift;

	my $pid = $pids->{$daemon};
	my $pid_path = "$server::conf/$daemon.pid";

	if ( ! $pid && -e $pid_path ) {
		my $p = read_file $pid_path;
		if ( kill 0, $p ) {
			warn "adopted $daemon $p\n";
			return $pids->{$daemon} = $p;
		} else {
			warn "old $daemon $p not running";
			unlink $pid_path;
		}
	}

	$pid ||= 'not started';
	warn "start_stop $daemon $pid\n";

	if ( $pid =~ m{^\d+$} ) {
		my $pstree = `pstree -p $pid`;
		my @pids = $pstree =~ m{\((\d+)\)}g;
		warn "pstree $pstree pids ",dump( @pids );
		kill 1, $_ foreach reverse @pids;
		$pids->{$daemon} = 'stopped';
		return qq|$daemon pid $pid stopped|;
	} else {
		if ( $pid = fork ) {
			# parent
			$pids->{$daemon} = $pid;
			write_file $pid_path, $pid;
			warn "forked $daemon $pid\n";
			return qq|$daemon pid $pid started|;
		} elsif ( defined $pid ) {
			# child
			my $invoke = 'start';
			$invoke = $1 if $daemon =~ s{/(.+)}{};
			if ( $daemon =~ m{dhcpd|tftpd|dnsd} ) {
				my $exec = "perl -I$server::base_dir/lib -I$server::base_dir/lib/PXElator -M$daemon -e ${daemon}::${invoke}";
				warn "exec $exec";
				x11::xterm( $daemon => $exec );
			} else {
				my $eval = $daemon . '::' . $invoke . '(' . ( @_ ? dump(@_) : '' ) . ')';
				warn "eval $eval";
				eval $eval;
				warn "can't start $daemon: $@" if $@;
			}
			exit;
		} else {
			die "fork error $!";
		}
	}
}

