#!/usr/local/bin/perl
# save_mon.cgi
# Create, update or delete a monitor

require './status-lib.pl';
$access{'edit'} || &error($text{'mon_ecannot'});
&ReadParse();
if ($in{'type'}) {
	$serv->{'type'} = $in{'type'};
	$serv->{'id'} = time();
	}
else {
	$serv = &get_service($in{'id'});
	$serv->{'oldremote'} = $serv->{'remote'};
	}

if ($in{'delete'}) {
	# Delete the monitor
	&delete_service($serv);
	&webmin_log("delete", undef, $serv->{'id'}, $serv);
	}
else {
	# Parse and validate inputs
	&error_setup($text{'mon_err'});
	$in{'desc'} || &error($text{'mon_edesc'});
	$serv->{'desc'} = $in{'desc'};
	if ($in{'remote_def'}) {
		delete($serv->{'remote'});
		}
	else {
		if ($in{'type'} || $serv->{'remote'} ne $in{'remote'}) {
			# Only need to check for new monitors
			eval { $ch = &remote_foreign_check($in{'remote'},
							   'status') };
			&error(&text('mon_elogin', $in{'remote'}))
			    if ($@ =~ /invalid.*login/i || $@ =~ /HTTP.*401/i);
			&error(&text('mon_eremote', $in{'remote'})) if ($@);
			$ch || &error(&text('mon_estatus', $in{'remote'}));
			&remote_foreign_require($in{'remote'}, 'status',
						'status-lib.pl');
			#$handlers = &remote_eval($in{'remote'}, 'status',
			#			 '[ &list_handlers() ]');
			#&indexof($serv->{'type'}, @$handlers) == -1 &&
			#	&error(&text('mon_ertype', $in{'remote'}));
			$ok = &remote_eval($in{'remote'}, 'status',
			   "-r \"\$root_directory/status/$serv->{'type'}-monitor.pl\"");
			$ok || &error(&text('mon_ertype', $in{'remote'}));
			}
		$serv->{'remote'} = $in{'remote'};
		}
	$serv->{'nosched'} = $in{'nosched'};
	$serv->{'ondown'} = $in{'ondown'};
	$serv->{'onup'} = $in{'onup'};
	$serv->{'runon'} = $in{'runon'};
	$serv->{'clone'} = $in{'clone'};
	$type = $serv->{'type'};
	do "./${type}-monitor.pl";
	$func = "parse_${type}_dialog";
	if (defined(&$func)) {
		&$func($serv);
		}

	# Save or create the monitor
	&save_service($serv);
	&webmin_log($in{'type'} ? "create" : "modify", undef,
		    $serv->{'id'}, $serv);
	}
&redirect("");

