#!/usr/bin/perl

# Simple script for rebuilding your enzyme db.
# Borrowed from rusty@kuro5hin.org - see
# http://scoop.kuro5hin.org for a great GPL forum system!


###############################
## WARNING WARNING WARNING WARNING ##
###############################

if ($ARGV[0] eq '--help') {
print <<END;

WARNING:
This script will erase and rebuild your enzyme DB.
It will *not* preserve any existing data! Be really 
careful using this!

Usage: 
    [perl ]./dbnuke [sql file] [db name]

Arguments:
    * [sql file] is the name of the file containing
      the sql to build the database (usually catalyst_tables.sql).

    * [db name] is the name of the enzyme database

Warning messages:
    If this is your first time setting up Enzyme,
    you will see a message about "cannot drop database"
    which can be safely ignored.
END
exit;
}
 
#############
# This script will DESTROY your old DB. Make sure thats what you want!!
#############
$file = $ARGV[0] || 'catalyst_tables.sql';
$db = $ARGV[1] || 'enzyme';

print "\nThis will ERASE and reformat your enzyme database ($db).\nUse ./dbnuke --help for instructions.\nAre you sure? (y/[n]): ";
$sure = <STDIN>;

if ($sure =~ /n/) {
	print "Ok. Bye.\n";
	exit 1;
} else {
	print "Ok, then. Here we go!\n\n";
	print "Enter the username for $db\@localhost: ";
	$uname = <STDIN>;
	chomp $uname;
	#chomp $uname;
	
	print "Enter $uname\'s password: ";
	$pass = <STDIN>;
	chomp($pass);
	
	$drop = qq{echo "drop database $db;" | mysql -u $uname --password=$pass -B};
	$makefresh = qq{echo "create database $db;" | mysql -u $uname --password=$pass -B};
	$data = qq{cat $file | mysql -u $uname --password=$pass -B $db};
	
	print "Error dropping $db!\n" if system($drop);
	print "Error making new $db!\n" if system($makefresh);
	
	print "\nDumping tables and data... ";
	print "Error dumping data into $db!\n" if system($data);
	print "Done.\n";

	print "Granting to webhost... ";
	system("echo \"grant insert, update, select, delete on $db.* to nobody\@localhost identified by '$webpass'\" | mysql -u $uname --password=$pass -B");
	print "Done.\n";
}
