#!/usr/bin/perl
# -*-cperl-*-
$| = 1;

use DBI;
use FindBin qw($Bin);
use lib "$Bin/../lib_files";

use bncConfigXML;
use bncLibCQPXML;

$bncHandle = DBI->connect("DBI:mysql:$bwMYSQLtable:$bwMYSQLhost:$bwMysqlPort", "$bwMysqlUser", "$bwMysqlPwd")
or die <<'STOP';
Error: Can't access MySQL database.  Make sure that the server is running and that your
       configuration settings are correct (in lib_files/bncConfigXML.pm).  If the problem
       persists, your version of BNCweb may be too old or damaged.  In this case, please
       re-install from scratch by running the script 'make_MySQL_tables.pl'.
STOP


print "Dropping database tables that are no longer used ... ";

$sqlQuery = "DROP TABLE if exists `lemmaTable`";
$bncHandle->do($sqlQuery);
$sqlQuery = "DROP TABLE if exists `lemma_overall`";
$bncHandle->do($sqlQuery);
$sqlQuery = "DROP TABLE if exists `lemma_spoken`";
$bncHandle->do($sqlQuery);
$sqlQuery = "DROP TABLE if exists `lemma_written`";
$bncHandle->do($sqlQuery);
$sqlQuery = "DROP TABLE if exists `speakerInfo`";
$bncHandle->do($sqlQuery);

# this table is currently not used, but may be in future versions!
$sqlQuery = "DROP TABLE if exists macros";
$bncHandle->do($sqlQuery);

print "ok\n";


$sqlQuery = "SHOW COLUMNS FROM `settings` WHERE Field = 'showRandom'";
my $rows = $bncHandle->do($sqlQuery);
if ($rows == 0) {
  print "Adding new column settings.showRandom ... ";
  $sqlQuery = "ALTER TABLE `settings` ADD COLUMN `showRandom` varchar(3) collate latin1_general_ci default 'no'";
  $bncHandle->do($sqlQuery)
    or die "ERROR -- ".$bncHandle->errstr;
  print "ok\n";
}
elsif ($rows != 1) {
  warn <<'STOP';
Warning: There's something wrong with your table 'settings'.  Please consider
         re-installing the MySQL databases from scratch by running the script
         'make_MySQL_tables.pl'.
STOP
}


print "Setting triggers for timestamps ... ";
foreach my $spec (qw(categorize:date_of_saving history:time_of_query savedQueries:date_of_saving tableLog:date_of_saving)) {
  my ($table, $field) = split /:/, $spec;
  $sqlQuery = "ALTER TABLE `$table` CHANGE COLUMN `$field` `$field` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP";
  $bncHandle->do($sqlQuery)
    or die "ERROR -- ".$bncHandle->errstr;
}
print "ok\n";


print "Updating genre information ... ";
# This may not be necessary, but apparently there was a problem with the Lancaster installation at some point.
# We recreate the genre tables to be on the safe side -- this should not be an overly expensive operation. 

my $prefix = "bnc";
open (OUT, ">$bwTempPath/${prefix}_genres.tbl") || die "can't open: $!";	
open (OUT2, ">$bwTempPath/${prefix}_genres2.tbl") || die "can't open: $!";	

$sqlQuery = "SELECT fname, fnum, genre FROM `headerInfo`";
$resArrayResult = $bncHandle->selectall_arrayref($sqlQuery)
  or die "ERROR\nFailed to execute '$sqlQuery': " . $bncHandle->errstr;
foreach my $line (@$resArrayResult) {
  my ($fname, $fnum, $genre) = @$line;
  my $string = "genre=$genre";
  my $value = $catValues{$string};
  print OUT2 "$fname\t$fnum\t$value\n";
  my @values = split(/:/, $value);
  foreach my $value (@values) {
    print OUT "$fname\t$fnum\t$value\n";
  }
}
close(OUT);
close(OUT2);

$sqlQuery = "DELETE FROM `genres`";
$bncHandle->do($sqlQuery)
  or die "ERROR\nTable 'genres' seems to be missing: ".$bncHandle->errstr;
$sqlQuery = "DELETE FROM `genres2`";
$bncHandle->do($sqlQuery)
  or die "ERROR\nTable 'genres2' seems to be missing: ".$bncHandle->errstr;

$sqlQuery = "LOAD DATA INFILE '$bwMySQLTempPath/${prefix}_genres.tbl' INTO TABLE genres FIELDS ESCAPED BY ''";
$bncHandle->do($sqlQuery)
  or die "ERROR on 'genres': ".$bncHandle->errstr;
$sqlQuery = "LOAD DATA INFILE '$bwMySQLTempPath/${prefix}_genres2.tbl' INTO TABLE genres2 FIELDS ESCAPED BY ''";
$bncHandle->do($sqlQuery)
  or die "ERROR on 'genres2': ".$bncHandle->errstr;

unlink("$bwMySQLTempPath/${prefix}_genres.tbl");
unlink("$bwMySQLTempPath/${prefix}_genres2.tbl");

print "ok\n";


print "Your BNCweb installation has successfully been upgraded.\n";
