#!/usr/local/bin/perl -w

use warnings;
use strict;
use Getopt::Std;
use FindBin qw($Bin);
use Carp;

# Figure out wher to find the test classes.
use lib "$Bin/../classes";

# Name of script that adds indices
use constant MKINDICES => 'deploy_indices';

$SIG{__DIE__} = \&Carp::confess;

$SIG{__WARN__} = sub {
    print STDERR "##################################################################\n";
    &Carp::cluck;
    print "\n";
};

our ($opt_u, $opt_p, $opt_h, $opt_T, $opt_D);
BEGIN {
    getopts('d:u:p:hTD:');
    $ENV{TANGRAM_TRACE} = $opt_T ? 1 : 0;
}

usage() if $opt_h;

# Load needed classes.
require Tangram;
require DBI;
require Myco;

use Myco::Config qw(:database);

my $user = $opt_u || DB_USER;
my $pass = $opt_p || DB_PASSWORD;
DBI->trace($opt_D || 0);

# create the database - it'll fail gently of it exists
system( @{+DB_CREATE_CMD} );

my $dbh = DBI->connect(DB_DSN, $user, $pass);
unless (Myco::Schema->schema) {
    Myco::Schema::mkschema();
}
# Deploy it!
{
   my $db_already_deployed = 0;
    my $msg = '';

    # squelch new 5.8-type warnings
    local $SIG{__WARN__} = sub {};

    # inspect $schema for new classes and deploy them
    my $schema = Myco::Schema->schema;
    for my $class_name ( keys %{$schema->{classes}} ) {
        my $class_obj = $schema->{classes}->{$class_name};
        my $table = $class_obj->{table};
        my $table_exists = $dbh->do("select * from $table");
        if ($table_exists) {
            $db_already_deployed = 1;
            delete $schema->{classes}->{$class_name};
        } else {
            $msg .= "$table deployed\n";
        }
    }

    if (! $db_already_deployed or $msg) {
        Tangram::Relational->deploy($schema, $dbh);
        print $msg . "\nSchema Deployed\n";
    } else {
        print "No New Schema to Deploy\n";
    }

    $dbh->disconnect;

}

$dbh->disconnect;

sub usage {
    my $prog = substr($0, rindex($0, '/')+1);

    print qq{
Usage: $prog [options]

Supported Options:
  -d Database name. Defaults to PGDATABASE environment variable or, failing
     that, to the name of the current user.
  -u Database user login. Defaults to PGUSER environment variable or, failing
     that, to the name of the current user.
  -p Database user password. Defaults to PGPASSWORD environment variable or,
     failing that, to an empty string.
  -D Enable DBI trace. Supply a value between 0 and 9 depending on how much
     trace information you want. See the DBI man page for more information.
     Disabled (0) by default.
  -T Enable Tangram trace. Off by default.
  -h Display this usage message and exit.

};
    exit;
}
