#! /usr/bin/perl -w

# Bootstraping NuScat database
# Run bootstrap_db help to see available options or just look below...
#
# Costas Andreopoulos - 11/11/03

if( $ARGV[0] eq "help" || $#ARGV == -1) {
   print "******************************************************************************\n";
   print "* Name:      bootstrap_db                                                    *\n";
   print "*                                                                            *\n";
   print "* Synopsis:  bootstrap_db [-h host] [-d dbase] -u user -p password           *\n";
   print "*                                                                            *\n";
   print "* Author:    Costas Andreopoulos <C.V.Andreopoulos\@rl.ac.uk>                *\n";
   print "* Last rev.: November 11, 2003                                               *\n";
   print "* Version:   1.0                                                             *\n";
   print "******************************************************************************\n";
   exit();
}

$iarg = 0;

foreach $argument (@ARGV) {

 if( $argument eq '-h' ) { $hostname = $ARGV[$iarg+1]; }
 if( $argument eq '-d' ) { $dbase    = $ARGV[$iarg+1]; }
 if( $argument eq '-u' ) { $username = $ARGV[$iarg+1]; }
 if( $argument eq '-p' ) { $password = $ARGV[$iarg+1]; }

 $iarg++;
}

$hostname = "localhost" unless defined($hostname);
$dbase    = "NuScat"    unless defined($dbase);

if( !defined($username) ) { die("bootstrap_db: you must define an RDBMS username"); }
if( !defined($password) ) { die("bootstrap_db: you must define an RDBMS password"); }

#-- Drop database
$command = "mysqladmin -u " . $username . " --password=" . $password . " drop " . $dbase;
print $command."\n";
system($command);

#-- Create database
$command = "mysqladmin -u " . $username . " --password=" . $password . " create " . $dbase;
print $command."\n";
system($command);

@create_tables = (  "createTable_ExpInfo.sql",
                    "createTable_BeamFlux.sql",
                    "createTable_Reference.sql",
                    "createTable_MeasurementHeader.sql",
                    "createTable_CrossSection.sql",
                    "createTable_eDiffCrossSection.sql",
                    "createTable_StructureFunction.sql" );

$auth = "mysql -A -h ".$hostname." -u ".$username." --password=".$password." ".$dbase;


# build the *.sql directory from the $VALIDATOR enviroment variable

$sql_base_dir = $ENV{'GENIE'} ."/data/sql_queries";

foreach $sql_command (@create_tables) {

  $command = $auth . " < " . $sql_base_dir . "/" . $sql_command;
  print $command."\n";
  system($command);
}
