package daemons;

use warnings;
use strict;

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

use x11;
use CouchDB;

our $pids;
$pids = {
	httpd => $$,
	kvm => 'not started',
	wireshark => 'not started',
} 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 audit {
	my $msg = shift;
	my $daemon = shift;
	CouchDB::audit( $msg, $daemon, { daemon => $daemon, message => $msg, @_ } );
}

sub start_stop {
	my $daemon = shift;

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

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

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

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

