#!/usr/bin/env perl

use warnings;
# vi: set ts=4 sw=4 :
#____________________________________________________________________________
#
#   MusicBrainz -- the open internet music database
#
#   Copyright (C) 2002 Robert Kaye
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   $Id$
#____________________________________________________________________________

# Given a database connection key, this script simply exec's "psql" with the
# appropriate args.

use strict;

use FindBin;
use lib "$FindBin::Bin/../lib";

use strict;
use DBDefs;
use Getopt::Long;

use aliased 'MusicBrainz::Server::DatabaseConnectionFactory' => 'Databases';

my $system = 0;
my $help = 0;
my $schema;

GetOptions(
    "system"    => \$system,
    "help"      => \$help,
    "schema=s"  => \$schema,
) or exit 2;

my $key = shift // "READWRITE";

if ($help) {
    die "Usage: psql [database]\n\n  database -- the DBDefs name of the database to connect to. (default is READWRITE)\n";
}

my $db = Databases->get($key) or die "No such database '$key'\n";

if ($system) {
    my $sys_db = Databases->get("SYSTEM");
    $db = $db->meta->clone_object($sys_db, database => $db->database, schema => $db->schema);
}

unless ($schema) {
    $schema = $db->schema;
}

$ENV{"PGPASSWORD"} = $db->password;

exec "psql", $db->shell_args;
