#!/usr/local/bin/perl
# save_config.cgi
#
###
require'./mon-lib.pl';
&ReadParse();
#&header();
#
### parse and split variables
local @groups=split(/\s+/,$in{'hostgroups'});
local @watch=split(/\s+/,$in{'watchgroups'});
#
#print "GROUPS=$in{'hostgroups'}<br>";
#print "WATCH=$in{'watchgroups'}<br>";
#
### write mon.cf file
system("/bin/cp $config{'cfbasedir'}/mon.cf $config{'cfbasedir'}/mon.cf.bak$$") if(-f "$config{'cfbasedir'}/mon.cf");
#open(CONF,">data/mon.cf");
open(CONF,">$config{'cfbasedir'}/mon.cf");
print CONF <<EOF;
##### Start of config file for MON - generated by webmin-module ###########
#
### global options
#
cfbasedir\t=$config{'cfbasedir'}
alertdir\t=$config{'alertdir'} 
mondir\t\t=$config{'mondir'}
logdir\t\t=$config{'logdir'} 
statedir\t=$config{'statedir'}
histlength\t=$config{'histlength'}
randstart\t=$config{'randstart'}
authtype\t=$config{'authtype'}
authfile\t=$config{'authfile'}
EOF
print CONF "userfile\t=$config{'userfile'}<br>" if($config{'userfile'});
#
#
print CONF <<EOF;
#
#
### group definitions (hostnames or IP addresses)
### IMPORTANT NOTE: Ensure that hostgroup and watch entries are terminated with a blank line
#
EOF
foreach $p(@groups){
	print CONF "hostgroup $p ",$in{"members_$p"},"\n\n";
}
#
foreach $w(@watch){
	chomp($w);
	print CONF "\n#";
	print CONF "\nwatch $w\n";
	local @services=split(/\s+/,$in{"services_$w"});
	foreach $s(@services){
		chomp($s);
		print CONF "\tservice $s\n";
		local @def=split(/\0/,$in{"def_$w.$s"});
		foreach $d(@def){
			chomp($d);
			if($in{"value_$w.$s.$d"}=~/\.alert$/){
				next;
			}else{
				print CONF "\t\t$d ", $in{"value_$w.$s.$d"}, "\n";
			}
		}
		print CONF "\t\talert ", $in{"value_$w.$s.alert"}," ", $in{"alertval_$w.$s"},"\n";
	}
}
#
print CONF "#\n##### End of config file for MON - generated by webmin-module ###########\n";
close(CONF);
#
#stop and start mon
local $status = &backquote_logged("/etc/init.d/mon status 2>&1 </dev/null");
if ($status=~/running/){
	system("/etc/init.d/mon stop 1>/dev/null 2>&1");
}
system("/etc/init.d/mon start 1>/dev/null 2>data/monstart.err");
$test=`cat data/monstart.err`;
#print "TEST=$test<br>";
if($test){
	&error("Error Starting MON: $test");
}else{
	&redirect("./index.cgi");
}
