#!/usr/bin/perl

# $Id: postgresasm_restore,v 1.3 2001/09/14 19:05:20 bservies Exp $
# 
# Copyright 2001 Sun Microsystems, Inc.  All Rights Reserved.
#
use strict;
use Getopt::Long;
use Cwd;
use File::Basename;

use vars qw ($arg @db);
use vars qw ($opt_debug $opt_file $opt_verbose);

sub dprintf {
        my ($level, $format, @args) = @_;
        if (defined $opt_debug && $level <= $opt_debug) {
                print STDERR "$0: ";
                print STDERR sprintf $format, @args;
        }
}

sub execute_cmd {
	my @cmd = @_;
	my ($msg, $rc);

	$rc = 0xffff & system(@cmd);
	if ($rc == 0) {
		$msg = "ran with normal exit.";
	} elsif ($rc == 0xff00) {
		$msg = "command failed: $!";
	} elsif ($rc > 0x80) {
		$rc >>= 8;
		$msg = "ran with non-zero exit status $rc";
	} else {
		$msg = "ran with ";
		if ($rc & 0x80) {
			$rc &= ~0x80;
			$msg .= "core dump from ";
		}
		$msg .= "signal $rc";
	}
	dprintf(3, "command \"%s\" exited with %d.  Reason: \"%s\"\n", join " ", @cmd, $msg, $rc);
	return ($msg, $rc);
}


sub restore_db {
	my ($arg) = @_;
	my ($db, $msg, $rc, $path, $suffix);
	my @cmd = ("/usr/bin/psql");

	if (defined $opt_verbose) {
		push @cmd, ("-e");
	}

	# Determine the database name
	($db, $path, $suffix) = fileparse($arg, '');
	dprintf(3, "database \"%s\" at path \"%s\" with suffix \"%s\".\n",
	    $db, $path, $suffix);
	push @cmd, ("$db");

	# Run psql to restore the database itself
	($msg, $rc) = execute_cmd(@cmd);
}


sub myarg {
	my ($arg) = @_;
	dprintf(3, "argument: %s\n", $arg);
	push @db, ($arg);
}


#
# Main
#

# Unbuffer stderr and stdout
select STDERR; $| = 1;
select STDOUT; $| = 1;

# Process any command line options
&GetOptions("debug:i", "file=s", "verbose:i", "<>", \&myarg);
$opt_file = "-" unless (defined $opt_file);
dprintf(3, "current directory: %s\n", cwd());

foreach $arg (@db) {
	restore_db($arg);
}

