#!/usr/bin/perl
#
#  This tool generates all the tables needed for all installed modules
#
#
########################################################################
#
# $Author: rz $
# $Date: 2005/11/25 09:26:16 $
# $Header: /home/vvk/RPM/SOURCES/Project_Cherry/CVSROOT/cherry/bin/mkdb,v 2.0.0.1 2005/11/25 09:26:16 rz Exp $
# $Id: mkdb,v 2.0.0.1 2005/11/25 09:26:16 rz Exp $
# $Locker:  $
#
# $Log: mkdb,v $
# Revision 2.0.0.1  2005/11/25 09:26:16  rz
# Project Cherry release 2.0
#
# Revision 1.3  2003/07/30 19:05:20  rz
# Removed useless RCS remarks
#
# Revision 1.2  2003/07/30 09:41:01  rz
# Absolute path to ../etc removed
#
# Revision 1.1.1.1  2003/07/30 08:31:28  rz
# Project CHerry: imported from RCS
#

$|=1;

use DBI;

# Require system configuration data
require "/etc/cherry/cherry.cfg";


print "You should read INSTALLATION guide before running this tool.\nAre you sure all the database related stuff worked out ok ? [y/n]: ";

$yesno = <>;

if( ! ($yesno =~ /^y/) ) {
	print "Do it then!\n";
	exit;
}


$dbh = DBI->connect("dbi:$CFG::DB_TYPE:dbname=$CFG::DB_NAME;host=$CFG::DB_HOST",
	            "$CFG::DB_MASTER", 
	   	    "$CFG::DB_MASTER_PASSWORD",
		    { RaiseError => 0, AutoCommit => 1 });

if( ! $dbh ) {

	print "Cannot access database. Either DB server is not runnig or database '$DB_NAME' was not created aprior. Read INSTALLATION guide for more details on creating database.\n";

}

foreach $module ( @CFG::MODULES ) {

	next if( ! (-f "/usr/lib/cherry/$module/create_tables.$CFG::DB_TYPE"));

	$sql = "";

	open(SQL, "/usr/lib/cherry/$module/create_tables.$CFG::DB_TYPE");

	print "*** Creating tables for: $module... \n\n\n";
	
	while(! eof(SQL)) { 

		undef $sql;

		while(<SQL>) {
			$sql = $sql . "$_"; 
			last if (/;$/);
		}


		$sql = eval_($sql);


		$sth = $dbh->prepare($sql) if ($sql);

		if( !$sth ) {
			print "SQL PREPARE FAILED\n";
			next;
		}

		$rv = $sth->execute;

		if( $rv ) {
			print "OK\n";
		} else {
			print "FAILED\n";
		}
	}
	close(SQL);


}


exit;



sub eval_ {
        my ($s) = shift @_;

        my $delimeter="EOT" . rand 0xFFFFFFFF;
        $s="\$z=sprintf<<\"$delimeter\";\n$s\n$delimeter\n";
        eval $s;
	return $z;
}

