use Modern::Perl;

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

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

use vars qw($SQL_FOR_TABLE $FOREIGN_KEYS $VIEWS);
require "$Bin/../setup/lims.sql";

####### WHICH DB TO WIPEOUT & RECREATE:
say "THIS WILL DROP AND RE-CREATE DATABASE";
say "Name of db:";
my $DB = <STDIN>; # say $DB; exit;
chomp $DB;

$ENV{CENTRE} = $DB; # warn $DB; # exit;

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

# need admin user for views, etc
my $userid = $cfg->{settings}->{admin_db_user};
my $pwd    = $cfg->{settings}->{admin_db_pwd};
my $dsn    = $cfg->{dbh_params}->[0];
# p $userid; p $pwd; p $dsn; exit;

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

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

# tables:
foreach my $tbl( sort keys %$SQL_FOR_TABLE ) { say $tbl;
    $dbh->do( qq!DROP TABLE IF EXISTS $tbl! );
    $dbh->do( $SQL_FOR_TABLE->{$tbl} );
}
# views:
foreach my $view( keys %$VIEWS ) { say $view;
	$dbh->do( $VIEWS->{$view} );
}
# foreign keys:
foreach my $fk( sort keys %$FOREIGN_KEYS ) { say $fk;
    $dbh->do($FOREIGN_KEYS->{$fk});
}

$dbh->disconnect;

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