#!/usr/local/bin/perl
# restart.cgi
# Send a SIGHUP to apache

require './apache-lib.pl';
&ReadParse();
&error_setup($text{'restart_err'});

$conf = &get_config();
$pidfilestr = &find_directive_struct("PidFile", $conf);
$pidfile = $pidfilestr ? $pidfilestr->{'words'}->[0]
		       : "logs/httpd.pid";
$pidfile = &server_root($pidfile, $conf);

if ($httpd_modules{'core'} >= 1.301 && $config{'test_config'}) {
	# Test the configuration first
	if (-x $config{'apachectl_path'}) {
		$cmd = "$config{'apachectl_path'} configtest";
		}
	else {
		$out = "$config{'httpd_path'} -d $config{'httpd_dir'} -t";
		if ($config{'httpd_conf'}) {
			$cmd .= " -f $config{'httpd_conf'}";
			}
		}
	$out = `$cmd 2>&1`;
	if ($out && $out !~ /syntax\s+ok/i) {
		&error("<pre>$out</pre>");
		}
	}

if (-x $config{'apachectl_path'}) {
	# use apachectl to restart
	if ($httpd_modules{'core'} >= 2) {
		# Do a graceful restart
		$out = &backquote_logged("$config{'apachectl_path'} graceful 2>&1");
		if ($?) {
			&error("<pre>$out</pre>");
			}
		}
	else {
		$out = &backquote_logged("$config{'apachectl_path'} restart 2>&1");
		if ($out !~ /httpd restarted/) {
			&error("<pre>$out</pre>");
			}
		}
	}
else {
	# send SIGHUP directly
	open(PID, $pidfile) || &error(&text('restart_epid', $pidfile));
	<PID> =~ /(\d+)/ || &error(&text('restart_epid2', $pidfile));
	close(PID);
	&kill_logged('HUP', $1) || &error(&text('restart_esig', $1));
	}

# Check if restart was successful.. some config file error may have caused it
# to silently fail
sleep(1);
if (!open(PID, $pidfile) || <PID> !~ /(\d+)/ || !kill(0, $1)) {
	# Not running..  find out why
	$errorlogstr = &find_directive_struct("ErrorLog", $conf);
	$errorlog = $errorlogstr ? $errorlogstr->{'words'}->[0]
				 : "logs/error_log";
	if ($errorlog eq 'syslog' || $errorlog =~ /^\|/) {
		&error($text{'restart_eunknown'});
		}
	else {
		$errorlog = &server_root($errorlog, $conf);
		$out = `tail -5 $errorlog`;
		&error("<pre>$out</pre>");
		}
	}
&webmin_log("apply");
&redirect($in{'redir'});

