#!/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!";

# Create the status file
$sfile = "$module_config_directory/$dump->{'id'}.$$.status";
%status = ( 'status' => 'running',
	    'start' => time() );
&write_file($sfile, \%status);

if ($dump->{'email'} && &foreign_check("mailboxes")) {
	# Save output for mailing
	&foreign_require("mailboxes", "mailboxes-lib.pl");
	$temp = &tempname();
	open(OUT, ">$temp");
	}
else {
	# Throw output away
	open(OUT, ">/dev/null");
	}

# Create tape change wrapper
&create_wrappers();

# Do the backup
&execute_before($dump, OUT, 0);
$ok = &execute_dump($dump, OUT, 0, 1);
&execute_after($dump, OUT, 0);
close(OUT);

if ($temp) {
	# Construct the email
	$host = &get_system_hostname();
	local $subject = $dump->{'subject'} ||
			 "Backup of $dump->{'dir'} on $host";
	local $data = "Backing up $dump->{'dir'} on $host\n\n";
	open(OUT, $temp);
	while(<OUT>) {
		s/\r//g;
		$data .= $_;
		}
	close(OUT);
	$data .= "\n";
	if ($ok) {
		$data .= "Backup succeeded\n";
		}
	else {
		$data .= "Backup failed!\n";
		}
	unlink($temp);

	# Send the email
	local $mail = { 'headers' =>
			[ [ 'From', &mailboxes::get_from_address() ],
			  [ 'To', $dump->{'email'} ],
			  [ 'Subject', $subject ] ],
			'attach' =>
			[ { 'headers' => [ [ 'Content-type', 'text/plain' ] ],
			    'data' => $data } ] };
	&mailboxes::send_mail($mail, undef, 0, 0, $config{'smtp_server'});
	}

# Re-update the status file
if ($ok) {
	$status{'status'} = 'complete';
	}
else {
	$status{'status'} = 'failed';
	}
$status{'end'} = time();
&write_file($sfile, \%status);

