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

# Check if this backup is already running
&foreign_require("proc", "proc-lib.pl");
@procs = &proc::list_processes();
@running = &running_dumps(\@procs);
($running) = grep { $_->{'id'} eq $dump->{'id'} &&
		    $_->{'pid'} != $$ } @running;

$sfile = "$module_config_directory/$dump->{'id'}.$$.status";
if ($running) {
	# Already running! Do nothing ..
	$ok = 0;
	$out = "Backup is already running with PID $running->{'pid'}.\n";
	}
else {
	# Update status file
	%status = ( 'status' => 'running',
		    'pid' => $$,
		    'start' => time() );
	&write_file($sfile, \%status);

	if ($dump->{'email'}) {
		# Save output for mailing
		$temp = &transname();
		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);

	# Re-update the status file
	if ($ok) {
		# Worked .. but verify if asked
		if ($dump->{'reverify'}) {
			print OUT "\nVerifying backup ..\n";
			$ok = &verify_dump($dump, OUT, 0, 1);
			}
		if ($ok) {
			$status{'status'} = 'complete';
			}
		else {
			$status{'status'} = 'verifyfailed';
			}
		}
	else {
		$status{'status'} = 'failed';
		}
	close(OUT);
	$status{'end'} = time();
	&write_file($sfile, \%status);

	if ($temp) {
		# Read output
		open(OUT, $temp);
		while(<OUT>) {
			s/\r//g;
			$out .= $_;
			}
		close(OUT);
		unlink($temp);
		}
	}

if ($out && $dump->{'email'} && &foreign_check("mailboxes")) {
	# Construct the email
	&foreign_require("mailboxes", "mailboxes-lib.pl");
	$host = &get_system_hostname();
	@dirs = &dump_directories($dump);
	$dirs = join(", ", @dirs);
	local $subject = $dump->{'subject'} ||
			 "Backup of $dirs on $host";
	local $data = "Backing up $dirs on $host\n\n";
	$data .= $out;
	$data .= "\n";
	if ($ok) {
		$data .= "Backup succeeded\n";
		}
	else {
		$data .= "Backup failed!\n";
		}

	# Send the email
	local $mail = { 'headers' =>
			[ [ 'From', &mailboxes::get_from_address() ],
			  [ 'To', $dump->{'email'} ],
			  [ 'Subject', $subject ] ],
			'attach' =>
			[ { 'headers' => [ [ 'Content-type', 'text/plain' ] ],
			    'data' => $data } ] };
	if (!$ok || !$config{'error_email'}) {
		# Only send email upon failure, of it requested always
		&mailboxes::send_mail($mail, undef, 0, 0,
				      $config{'smtp_server'});
		}
	}

# Check for any dumps scheduled to run after this one
foreach $follow (&list_dumps()) {
	if ($follow->{'follow'} == $dump->{'id'} && $follow->{'enabled'} == 2) {
		system("$cron_cmd $follow->{'id'}");
		}
	}

