#!/usr/local/bin/perl
# save_cmd.cgi
# Save, create or delete a custom command

require './custom-lib.pl';
&ReadParse();

$access{'edit'} || &error($text{'save_ecannot'});
@cmds = &list_commands();
if ($in{'delete'}) {
	$cmd = $cmds[$in{'idx'}];
	&delete_command($cmd);
	&webmin_log("delete", "command", $cmd->{'id'}, $cmd);
	}
else {
	&error_setup($text{'save_err'});
	if (!$in{'new'}) {
		$cmd = $cmds[$in{'idx'}];
		}
	else {
		$cmd = { 'id' => time() };
		}

	# parse and validate inputs
	$in{'cmd'} =~ /\S/ || &error($text{'save_ecmd'});
	if ($in{'dir_def'}) {
		$cmd->{'cmd'} = $in{'cmd'};
		}
	else {
		$in{'dir'} =~ /^\S+$/ || &error($text{'save_edir'});
		$cmd->{'cmd'} = "cd $in{'dir'} ; $cmd->{'cmd'}";
		}
	$in{'desc'} =~ /\S/ || &error($text{'save_edesc'});
	$cmd->{'desc'} = $in{'desc'};
	$in{'html'} =~ s/\r//g;
	$cmd->{'html'} = $in{'html'};
	$in{'user_def'} || (@u = getpwnam($in{'user'})) ||
		&error($text{'save_euser'});
	$cmd->{'user'} = $in{'user_def'} ? "*" : $in{'user'};
	$cmd->{'raw'} = $in{'raw'};
	$cmd->{'su'} = $in{'su'};
	$cmd->{'order'} = $in{'order_def'} ? 0 : int($in{'order'});
	$cmd->{'noshow'} = $in{'noshow'};
	$cmd->{'usermin'} = $in{'usermin'};
	$cmd->{'args'} = [ ];
	for($i=0; defined($name = $in{"name_$i"}); $i++) {
		if ($name) {
			push(@{$cmd->{'args'}}, { 'name' => $name,
						  'desc' => $in{"desc_$i"},
						  'type' => $in{"type_$i"},
						  'quote' => $in{"quote_$i"},
						  'opts' => $in{"opts_$i"} });
			}
		}
	&save_command($cmd);
	&webmin_log($in{'new'} ? "create" : "modify", "command",
		    $cmd->{'id'}, $cmd);

	if ($in{'new'} && $access{'cmds'} ne '*') {
		$access{'cmds'} .= " ".$cmd->{'id'};
		&save_module_acl(\%access);
		}
	}
&redirect("");

