# -*- perl -*-
# ers_masterremovefunctions
# Copyright (C) 2002 Digital Distribution GFS P/L
# Derived from code Copyright (C) 2000 PostgreSQL, Inc.

eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}'
    & eval 'exec perl -S $0 $argv:q'
    if 0;

use Pg;
use Getopt::Long;

$| = 1;

$result = GetOptions("debug!", "quiet!", "help",
		     "host=s", "user=s", "password=s");

$RServ::debug = $opt_debug || 0;
$RServ::quiet = 1 if $opt_quiet;

if (defined($opt_help) || (scalar(@ARGV) < 1)) {
    print "Usage: $0 --host=name --user=name --password=string masterdb\n";
    exit ((scalar(@ARGV) < 1)? 1:0);
}

my $master = $ARGV[0] || "master";

my $minfo = "dbname=$master";
$minfo = "$minfo host=$opt_host" if (defined($opt_host));
$minfo = "$minfo user=$opt_user" if (defined($opt_user));
$minfo = "$minfo password=$opt_password" if (defined($opt_password));

sub RollbackAndQuit {
    $conn = shift @_;

    print STDERR "Error in query: ", $conn->errorMessage;
    $conn->exec("ROLLBACK");
    exit (-1);
}

my $conn = Pg::connectdb($minfo);
if ($conn->status != PGRES_CONNECTION_OK) {
    print STDERR "Failed opening $minfo\n";
    exit 1;
}

my $result = $conn->exec("BEGIN");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("set transaction isolation level serializable");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

#
# Functions
#
$result = $conn->exec("DROP FUNCTION _rserv_log_()");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("DROP FUNCTION _rserv_sync_(int4)");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("DROP FUNCTION _rserv_debug_(int4)");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("DROP FUNCTION _rserv_lock_altid_(int4)");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("DROP FUNCTION _rserv_unlock_altid_(int4)");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

# PTE funcs
$result = $conn->exec("DROP FUNCTION _pte_get_snapshot_()");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("DROP FUNCTION _pte_set_snapshot_(text)");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

$result = $conn->exec("COMMIT");
RollbackAndQuit($conn) if ($result->resultStatus ne PGRES_COMMAND_OK);

exit (0);
