#!/usr/bin/perl

use v5.14;
use warnings;
use autodie;
use File::Slurp;
use Attean;
use AtteanX::Store::DBI;
use DBI;
use DBIx::MultiStatementDo;
use Getopt::Long qw(:config no_ignore_case);

my @types	= AtteanX::Store::DBI->available_database_types;
my %types	= map { $_ => 1 } @types;
if (scalar(@types) == 0) {
	warn "No database types are available for use with Attean.";
	exit(0);
}

my $COMMANDS_STRING	= join("\n", map { "  $_" } qw(init drop));
my $TYPES_STRING	= join("\n", map { "  $_" } @types);
if (scalar(@ARGV) < 1) {
	print STDERR <<"END";
Usage: $0 COMMAND DATATYPE-TYPE [-h HOST] [-P PORT] [-u USER] [-p PASSWORD] DATABASE-NAME

COMMAND must be one of:

$COMMANDS_STRING

DATABASE-TYPE must be one of:

$TYPES_STRING

END

	exit(0);
}

my $verbose		= 0;
my $dryrun		= 0;
my $host;
my $port;
my $user;
my $password;
my %args;
my $result			= GetOptions(
	"verbose"		=> \$verbose,
	'n'				=> \$dryrun,
	"host=s"		=> \$args{host},
	"port|P=s"		=> \$args{port},
	"user=s"		=> \$args{user},
	"password|p=s"	=> \$args{password},
);
my $command	= shift;
die "Unrecoognized command '$command'. Must be one of:$COMMANDS_STRING\n\n" unless ($command =~ /^(init|drop)$/);

my $type	= shift;
die "No database type given. Must be one of:\n\n$TYPES_STRING\n\n" unless (defined($type) and length($type));
die "Unrecoognized database type '$type'. Must be one of:\n\n$TYPES_STRING\n\n" unless (exists $types{$type});

$args{database}	= shift || die "No database name given.\n";


my @connect	= AtteanX::Store::DBI->dbi_connect_args($type, %args);
my $dbh		= DBI->connect(@connect);
my $store	= AtteanX::Store::DBI->new( dbh => $dbh );
my $batch	= DBIx::MultiStatementDo->new( dbh => $dbh );

if ($command eq 'init') {
	if (my $file = $store->create_schema_file) {
		my $sql	= read_file($file);
		if ($dryrun) {
			print "$sql\n";
		} else {
			$batch->do($sql);
			$store->initialize_version;
		}
	} else {
		warn "No schema file available for this database.\n";
		exit(1);
	}
} elsif ($command eq 'drop') {
	if (my $file = $store->drop_schema_file) {
		my $sql	= read_file($file);
		if ($dryrun) {
			print "$sql\n";
		} else {
			$batch->do($sql);
		}
	} else {
		warn "No schema file available for this database.\n";
		exit(1);
	}
}
