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

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

$db = $ARGV[0];
$db || die "Missing database parameter";
$file = &date_subs($config{'backup_'.$db});
if (!$file) {
	print STDERR "No backup file set for database $db\n";
	exit(1);
	}
$format = $config{'backup_format_'.$db};

&execute_before($db, STDOUT, 0, $file);
unlink($file);
$bkup_command = $config{'dump_cmd'}.
		($postgres_login ? " -U $postgres_login" : "").
		($config{'host'} ? " -h $config{'host'}" : "").
		($format eq 'p' ? "" : " -b").
		" -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 = &tempname();
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;
	}
else {
	$ex = 0;
	}
&execute_after($db, STDOUT, 0, $file);
exit($ex);

