#!/usr/bin/perl -wW

use strict;

use CyberArmy;

my $conf = $CyberArmy::Config{'DINAH_BASE'}.'/conf/httpd.conf';
my $httpd = $CyberArmy::Config{'HTTPD'};

my ($port,$parallel,$pidfile);

open CONF, '<'.$conf;
while(<CONF>) {
	if (/^Port (\d+)/) { $port = $1 }
	elsif (/^PidFile (.*)/) { $pidfile = $1 }
	elsif (/^#DinahAddParallel (\d+)/) { $parallel = $1 }
	last if ($port && $pidfile && $parallel);
}
close CONF;

die "No specified PidFile\n" unless $pidfile;
$parallel ||= 0; $port ||= 80 if ($parallel);

my $cmd = shift || '';

for (my $current = 0; $current <= $parallel; $current++) {
	## first see if it is running or not
	my $number =  $current + 1;
	my $is_running = 0;
	my $pid = 0;
	my $para_pidfile = $parallel ? 
		$pidfile.'.'.$number : $pidfile;

	if (-f $para_pidfile) {
		open PID, '<'.$para_pidfile;
		chomp ($pid = do {local$/; <PID>});
		close PID;
	
		$is_running = (kill 0, $pid) ? 1 : 0;
	}

	if ($cmd eq 'start') {
		if ($is_running) {	
			print '#',$number,' ('.$pid.') is already running',"\n";
		} else {
			print &start($number)
				? ('#',$number,': started',"\n")
				: ('#',$number,': cannot be started',"\n");
		}
	} elsif ($cmd eq 'stop') {
		if ($is_running) {
			print kill(2, $pid) ?
				('#',$number,': stopped',"\n") :
				('#',$number,': could not be stopped',"\n");
		} else {
			print '#',$number,($pid?' ('.$pid.'?) ':' '),'is not running',"\n";
		}
	} elsif ($cmd eq 'restart') {
		if ($is_running) {
			my $problems = 0;
			if (kill 2, $pid) {
				print '#',$number,': stopped',"\n";
				if (&start($number)) {
					print '#',$number,': restarted',"\n"
				} else {
					print '#',$number,': could not be restarted',"\n";
					$problems++;
				}
			} else {
				print '#',$number,': could not be stopped',"\n";
				$problems++;
			}
			
			if ($problems && ($current < $parallel)) {
				warn "WARNING: Stoping restart procedure at $current\n";
				exit($number)
			} else { sleep 30 if ($current < $parallel) }
		} else { 
			print '#',$number,($pid?' ('.$pid.'?) ':' '),
					'is not running',"\n";
		}
	} elsif ($cmd eq 'test') {
		print 'Testing syntax at ',$conf,"\n";
		exit(system($httpd,'-t'));
	} else {
		print <<OUT;
usage: $0 (start|stop|restart|test)
OUT
		exit(1);
	}
}

sub start {
	system(
		$httpd, '-f', $conf,
		($port ? ('-c','Port '.($port - 1 + $_[0])) : ''),
		($pidfile && $parallel ? ('-c','PidFile '.$pidfile.'.'.$_[0]) : '')
	) ? 0 : 1
}
