#!/usr/bin/env perl

####################################################################
# Copyright @ 1995-1999 University of Rochester
# All Rights Reserved
####################################################################

BEGIN {
	my $useLibDir = '.';
	if    ($0 =~ m|^(/.*)/|)  { $useLibDir = $1; }
	elsif ($0 =~ m|^(\..*)/|) { $useLibDir = $1; }
	elsif ($0 =~ m|^(.+)/|)   { $useLibDir = "./$1"; }
	unshift @INC, $useLibDir;
}

use webworkInit; # WeBWorKInitLine

use Global;
use Auth;
use strict;

if (@ARGV != 2)
  {
   print "\nSyntax is import_webwork-database.pl courseID textDatabaseFile\n";
   print "      (e.g. import_webwork-database.pl  demoCourse textDataBase)\n\n";
   exit(0);
  }

my $course = $ARGV[0];
my $textDatabaseFile = $ARGV[1];

# establish environment for this script

  &Global::getCourseEnvironment($course);

# Directory paths

my $databaseDirectory = getCourseDatabaseDirectory();
my $courseScriptsDirectory = getWebworkScriptDirectory();

# File names

  require "${courseScriptsDirectory}$Global::DBglue_pl";
  require "${courseScriptsDirectory}$Global::HTMLglue_pl";
  require "${courseScriptsDirectory}$Global::FILE_pl";

  my $databaseFile = $Global::database;

# get all psvn's for set

my ($line,$item);
my @probSetRecord = ();
my $probSetString = '';
my @PROBSETarray = ();

open (INFILE, "$textDatabaseFile") or wwerror("$0","can't open $textDatabaseFile for reading");

while (defined ($line = <INFILE>)) {
    chomp($line);
    unless ($line =~ /\S/) {next;}          ## skip blank lines 
    if ($line =~ /^[^\[]\s*(.*)/) {         ## non bracketed line  
        push @probSetRecord, $1;}
    
    else {                                  ## bracketed line
        $probSetString = join ("\&", @probSetRecord);
        push @PROBSETarray, $probSetString;
        $line =~ /^\[(.*)\]$/;
        push @PROBSETarray, $1;
        @probSetRecord =();  
    }
}

close (INFILE);

$probSetString = join ("\&", @probSetRecord); ## last record
push @PROBSETarray, $probSetString; ## add last record             
shift @PROBSETarray;                ## remove first item which is an empty probSetString

my $path_to_WW_DB = "${databaseDirectory}$Global::database";

## backup existing db

my $message = '';

if ( -e "$path_to_WW_DB" ) {
#		$message .= "Backing up current webwork data base: $path_to_WW_DB\n Two backups are kept.\n\n";
print "Backing up current webwork data base: $path_to_WW_DB\n Two backups are kept.\n\n";
		&backup($path_to_WW_DB);
	}

## Create new database


#$message .= "Creating new data base $path_to_WW_DB .\n";
print "Creating new data base $path_to_WW_DB .\n";

create_db($path_to_WW_DB, $Global::webwork_database_permission);

if ( -e $path_to_WW_DB ) {
	chmod($Global::webwork_database_permission,$path_to_WW_DB) ||
				 wwerror($0, "Can't do chmod($Global::webwork_database_permission,$path_to_WW_DB)");
	chown(-1,$Global::numericalGroupID,$path_to_WW_DB)  ||
				 wwerror($0,"Can't do chown(-1,$Global::numericalGroupID,$path_to_WW_DB)");

#	$message .=   "New data base created\n";
print "New (blank) data base created\n";
}
else {
#	$message .=   "New data base could not be created\n";
print "New data base could not be created\n";
}

# load up new database
my $wwDbObj;            # Object for referencing the database
my %hash;

&Global::tie_hash('WW_FH', \$wwDbObj, \%hash, $path_to_WW_DB, 'W', $Global::standard_tie_permission);
%hash = @PROBSETarray; 
&Global::untie_hash('WW_FH', \$wwDbObj, \%hash, $path_to_WW_DB);

# $message .=   "The new data base $path_to_WW_DB could not be created\n";
print "The new data base $path_to_WW_DB has been filled with data\n";

sub backup  {
	## takes as a parameter the full path name
	## makes upto two backups of the file with _bak1, or _bak2
	## appended to filename where _bak1 is the most recent backup

	my $fileName =$_[0];

	if (-e "${fileName}_bak1") {
		rename("${fileName}_bak1","${fileName}_bak2") or
		  &wwerror("$0","can't rename ${fileName}_bak1");
	}

	if (-e "${fileName}") {
		rename("${fileName}","${fileName}_bak1") or
		  &wwerror("$0","can't rename ${fileName}");
	}
}
