use strict;
use warnings;

use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use FindBin qw($Bin);
use Config::Auto;
use DBI;

####### WHICH DB TO WIPEOUT & RECREATE
# my $DB = 'tmp'; # 'lims_scratch'; # now need specifying on command-line
##############################

my $DB = $ARGV[0] or die 'ERROR: name of db to re-create is required';

use lib "$Bin/../lib"; # warn $Bin; exit;

require "$Bin/../setup/lims.sql";
#require "$Bin/../setup/data.sql"; # using core_data mysqldump now

use vars qw($SQL_FOR_TABLE $FOREIGN_KEYS $DATA);

my $cfg = Config::Auto::parse("$Bin/../config/lims_config.pl", format => 'perl');

my ($dsn, $userid, $pwd) = @{ $cfg->{dbh_params} }; # arrayref

my $dbh = DBI->connect(
		$dsn, $userid, $pwd,
		{RaiseError => 1, PrintError => 0}
	);

map { $dbh->do($_) }
    (
        qq!DROP DATABASE IF EXISTS `$DB`!,
        qq!CREATE DATABASE `$DB`!,
        qq!USE `$DB`!,
    );

foreach ( sort keys %$SQL_FOR_TABLE ) { print $_, "\n";
    $dbh->do( qq!DROP TABLE IF EXISTS $_! );
    $dbh->do( $SQL_FOR_TABLE->{$_} );
}

foreach my $fk( sort keys %$FOREIGN_KEYS ) {  print $fk, "\n";
    $dbh->do($FOREIGN_KEYS->{$fk});
}

# using core_data mysqldump now
#foreach ( @$DATA ) { print $_ . "\n";
#    $dbh->do($_);
#}

$dbh->disconnect;

#system('./dump_core_data.sh'); # needs $DB passing

gunzip "$Bin/../setup/core_data.gz" => "$Bin/core_data" # retains original .gz file
        or die "gunzip failed: $GunzipError\n";
system("mysql -u $userid -p$pwd $DB < $Bin/core_data");
unlink "$Bin/core_data";
