#!/usr/local/bin/perl
# backup.pl
# Called by cron to backup a database

$no_acl_check++;
require './postgresql-lib.pl';

if ($ARGV[0] eq "--all") {
	$all = 1;
	@dbs = &list_databases();
	}
else {
	$ARGV[0] || die "Missing database parameter";
	@dbs = ( $ARGV[0] );
	}

$ex = 0;
foreach $db (@dbs) {
	$format = $all ? $config{'backup_format_'}
		       : $config{'backup_format_'.$db};
	$suf = $format eq "p" ? "sql" :
	       $format eq "t" ? "tar" : "post";
	if ($all) {
		$file = &date_subs("$config{'backup_'}/$db.$suf");
		}
	else {
		$file = &date_subs($config{'backup_'.$db});
		}
	@tables = split(/\s+/, $config{'backup_tables_'.$db});
	$tables = join(" ", map { " -t ".quotemeta($_) } @tables);
	if (!$file) {
		print STDERR "No backup file set for database $db\n";
		exit(1);
		}

	&execute_before($db, STDOUT, 0, $file, $all ? undef : $db);
	unlink($file);
	$bkup_command = $config{'dump_cmd'}.
			($postgres_login ? " -U $postgres_login" : "").
			($config{'host'} ? " -h $config{'host'}" : "").
			($format eq 'p' ? "" : " -b").
			$tables.
			" -F$format -f ".quotemeta($file)." $db" ;

	if ( $postgres_sameunix && defined(getpwnam($postgres_login)) ) {
	    $bkup_command =~ s/"/\\"/g ;
	    $bkup_command =  "su $postgres_login -c ".quotemeta($bkup_command);
	}

	$temp = &transname();
	open(TEMP, ">$temp");
	print TEMP "$postgres_pass\n";
	close(TEMP);
	$out = &backquote_logged("$bkup_command 2>&1 <$temp");
	unlink($temp);
	if ($? || $out =~ /could not|error|failed/i) {
		print STDERR "Backup of database $db to file $file failed:\n";
		print STDERR $out;
		$ex = 1;
		}
	&execute_after($db, STDOUT, 0, $file, $all ? undef : $db);
	}
exit($ex);

