#!/usr/local/bin/perl
# save_hostsentry.cgi
# Save hostsentry options

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

# Validate inputs
-r $in{'wtmp'} || &error($text{'hostsentry_ewtmp'});
@ignore = split(/\s+/, $in{'ignore'});
foreach $u (@ignore) {
	defined(getpwnam($u)) || &error(&text('hostsentry_eignore', $u));
	}
for($i=0; defined($in{"mod_$i"}); $i++) {
	push(@mods, $in{"mod_$i"}) if ($in{"mod_$i"});
	}
if (defined($in{'foreign'})) {
	@foreign = split(/\s+/, $in{'foreign'});
	}
if (defined($in{'multiple'})) {
	@multiple = split(/\s+/, $in{'multiple'});
	foreach $m (@multiple) {
		gethostbyname($m) || &check_ipaddress($m) ||
			&error(&text('hostsentry_emultiple', $m));
		}
	}

# Write to the appropriate files
$conf = &get_hostsentry_config();
&lock_config_files($conf);
&save_config($conf, "WTMP_FILE", $in{'wtmp'});
&flush_file_lines();
&unlock_config_files($conf);

$ign = &find_value("IGNORE_FILE", $conf);
&lock_file($ign);
open(IGN, ">$ign");
foreach $i (@ignore) {
	print IGN $i,"\n";
	}
close(IGN);
&unlock_file($ign);

$mods = &find_value("MODULE_FILE", $conf);
&lock_file($mods);
open(MODS, ">$mods");
foreach $m (@mods) {
	print MODS $m,"\n";
	}
close(MODS);
&unlock_file($mods);

$basedir = &get_hostsentry_dir();
if (defined(@foreign)) {
	&lock_file("$basedir/moduleForeignDomain.allow");
	open(FOREIGN, ">$basedir/moduleForeignDomain.allow");
	foreach $f (@foreign) {
		print FOREIGN $f,"\n";
		}
	close(FOREIGN);
	&unlock_file("$basedir/moduleForeignDomain.allow");
	}
if (defined(@multiple)) {
	&lock_file("$basedir/moduleMultipleLogins.allow");
	open(MULTIPLE, ">$basedir/moduleMultipleLogins.allow");
	foreach $m (@multiple) {
		print MULTIPLE $m,"\n";
		}
	close(MULTIPLE);
	&unlock_file("$basedir/moduleMultipleLogins.allow");
	}

if ($in{'apply'}) {
	# Attempt to restart
	if ($config{'hostsentry_stop'}) {
		&system_logged("$config{'hostsentry_stop'} >/dev/null 2>&1 </dev/null");
		}
	else {
		$pid = &get_hostsentry_pid();
		&kill_logged("TERM", $pid) if ($pid);
		}
	$cmd = &hostsentry_start_cmd();
	$temp = &tempname();
	&system_logged("$cmd >$temp 2>&1 </dev/null");
	open(TEMP, $temp);
	while(<TEMP>) { $out .= $_; }
	close(TEMP);
	unlink($temp);
	&error("<tt>$out</tt>") if ($?);
	}
&webmin_log("hostsentry");

&redirect("");

