#!/usr/local/bin/perl
# start.cgi
# Start apache with the server root from the config files

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

&clean_environment();

$access{'stop'} || &error($text{'start_ecannot'});
if ($config{'start_cmd'}) {
	# use the configured start command
	if ($config{'stop_cmd'}) {
		# execute the stop command to clear lock files
		&system_logged("($config{'stop_cmd'}) >/dev/null 2>&1");
		}
	$out = &backquote_logged("($config{'start_cmd'}) 2>&1");
	&reset_environment();
	if ($?) {
		&error("<pre>$out</pre>");
		}
	}
elsif (-x $config{'apachectl_path'}) {
	# use the apachectl program
	$out = &backquote_logged("($config{'apachectl_path'} start) 2>&1");
	&reset_environment();
	if ($out =~ /\S/ && $out !~ /httpd started/) {
		&error("<pre>$out</pre>");
		}
	}
else {
	# start manually
	$httpd = &find_httpd();
	$cmd = "$httpd -d $config{'httpd_dir'}";
	if ($config{'httpd_conf'}) {
		$cmd .= " -f $config{'httpd_conf'}";
		}
	foreach $d (keys %httpd_defines) {
		$cmd .= " -D$d";
		}
	$temp = &tempname();
	$rv = &system_logged("( $cmd ) >$temp 2>&1 </dev/null");
	$out = `cat $temp`;
	unlink($temp);
	&reset_environment();
	if ($out =~ /\S/ && $out !~ /httpd started/) {
		&error("<pre>$cmd :\n$out</pre>");
		}
	}

# check if startup was successful. Later apache version return no
# error code, but instead fail to start and write the reason to
# the error log file!
sleep(3);
$conf = &get_config();
$pidfile = &get_pid_file();
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 ($out =~ /\S/) {
		&error("$text{'start_eafter'} : <pre>$out</pre>");
		}
	elsif ($errorlog eq 'syslog' || $errorlog =~ /^\|/) {
		&error($text{'start_eunknown'});
		}
	else {
		$errorlog = &server_root($errorlog, $conf);
		$out = `tail -5 $errorlog`;
		&error("$text{'start_eafter'} : <pre>$out</pre>");
		}
	}
&webmin_log("start");
&redirect($in{'redir'});

