#!/usr/local/bin/perl
# backup.pl
# Perform a backup and send the results to someone

$no_acl_check++;
require './fsdump-lib.pl';
$dump = &get_dump($ARGV[0]);
$dump->{'id'} || die "Dump $ARGV[0] does not exist!";

if ($dump->{'email'} && ($config{'smtp_server'} ||
    &foreign_check("sendmail") &&
    (%sconfig = &foreign_config("sendmail")) && -x $sconfig{'sendmail_path'})) {
	# Save output for mailing
	$temp = &tempname();
	open(OUT, ">$temp");
	}
else {
	# Throw output away
	open(OUT, ">/dev/null");
	}
&execute_before($dump, OUT, 0);
$ok = &execute_dump($dump, OUT, 0);
&execute_after($dump, OUT, 0);
close(OUT);
if ($temp) {
	if ($config{'smtp_server'}) {
		# Connect to SMTP server
		&open_socket($config{'smtp_server'}, 25, MAIL);
		&smtp_command(MAIL);
		&smtp_command(MAIL, "helo ".&get_system_hostname()."\n");
		&smtp_command(MAIL, "mail from: webmin\@".
				    &get_system_hostname()."\n");
		&smtp_command(MAIL, "rcpt to: ".$dump->{'email'}."\n");
		&smtp_command(MAIL, "data\n");
		}
	else {
		# Run sendmail executable
		open(MAIL, "|$sconfig{'sendmail_path'} -t >/dev/null 2>&1");
		}
	print MAIL "From: webmin\@".&get_system_hostname()."\n";
	print MAIL "To: $dump->{'email'}\n";
	if ($dump->{'subject'}) {
		print MAIL "Subject: $dump->{'subject'}\n";
		}
	else {
		print MAIL "Subject: Dump of $dump->{'dir'}\n";
		}
	print MAIL "\n";
	print MAIL "Backing up $dump->{'dir'}\n\n";
	open(OUT, $temp);
	while(<OUT>) {
		print MAIL $_;
		}
	close(OUT);
	print MAIL "\n";
	if ($ok) {
		print MAIL "Backup succeeded\n";
		}
	else {
		print MAIL "Backup failed!\n";
		}
	if ($config{'smtp_server'}) {
		&smtp_command(MAIL, ".\n");
		&smtp_command(MAIL, "quit\n");
		}
	close(MAIL);
	unlink($temp);
	}

# smtp_command(handle, command)
sub smtp_command
{
local ($m, $c) = @_;
print $m $c;
local $r = <$m>;
if ($r !~ /^[23]\d+/) {
	&error("SMTP command $c failed : $r");
        }
}

