#!/usr/local/bin/perl
# restore.cgi
# Restore a database from a local file

require './postgresql-lib.pl' ;

&ReadParse ( ) ;

&error_setup ( $text{'restore_err'} ) ;
$access{'restore'} || &error($text{'restore_ecannot'});
&can_edit_db($in{'db'}) || &error($text{'dbase_ecannot'});
if ( ! -f $in{'path'} ) {
	&error ( &text ( 'restore_pe2', $in{'path'} ) ) ;
}

$db_find_f = 0 ;

if ( $in{'db'} ) {

    foreach ( &list_databases() ) {

        if ( $_ eq $in{'db'} ) { $db_find_f = 1 ; }
    }
}

if ( $db_find_f == 0 ) { &error ( &text ( 'restore_edb' ) ) ; }

$rstr_command = $config{'rstr_cmd'}.
		($postgres_login ? " -U $postgres_login" : "").
		($config{'host'} ? " -h $config{'host'}" : "").
		($in{'only'} ? " -a" : "").
		($in{'clean'} ? " -c" : "").
		" -d $in{'db'} ".quotemeta($in{'path'});

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

$temp = &tempname();
open(TEMP, ">$temp");
print TEMP "$postgres_pass\n";
close(TEMP);
$out = &backquote_logged("$rstr_command 2>&1 <$temp");
unlink($temp);

if ( $? == 0 ) {
    &redirect ("edit_dbase.cgi?db=$in{'db'}") ;
} else {
    &error ( &text ( 'restore_exe', $rstr_command )."<pre>$out</pre>" ) ;
}
