#################################################################
#
# iDatabase::Admin::SQL
#
# Administration functions for iDatabase.
#
# Author: Matthew Mecham <matt@ikonboard.com>
#
#################################################################
package iDatabase::Admin::SQL;
use strict;

use vars qw/$SQL @ISA/;

require iDatabase::Admin::a_base;
@ISA = qw(iDatabase::Admin::a_base);

BEGIN { 
        if (eval "require DBI") {
            $SQL->{DBI} = 'Yes';
            require DBI;
        }
        use CGI::Carp "fatalsToBrowser";
 }


#-----------------------------------------------
# Our constructor
#-----------------------------------------------

sub new {
    my $pkg = shift;
    my $obj = { '_output' => undef, errors => [], success => 0 };
    bless $obj, $pkg;
    return $obj;
}

#-----------------------------------------------
# Check and create tables.
# 
# 'success'  => 1 or 0
# 'errors'   => [ @errors ]  An array of errors
#-----------------------------------------------


sub install_database {

    # Stop Ikonboard from forcing a die
    
    local $@;
    local $SIG{__DIE__};


    my $obj = shift;
    my $IN  = { 'schema_dir' => "/usr/local/mySQL/schema",   # Path to the directory containing the table schema
                'return_err' => "",                          # Boolean, return errors?
                'create_tbl' => "",                          # Boolean, create tables?
                'attr'       => {},                          # DB attributes, such as DB_USER, etc
                @_,
              };

    my $errors  = 0;
    my $found   = 0;
    my @fatal_errors;
    my ($have_dbi, $have_dbd, $can_connect, $found_db);

    # Test for the DBI library

    if ($SQL->{DBI} ne 'Yes') {
        ++$errors;
        push @{ $obj->{errors} }, "You must install the DBI suite of modules. Visit <a href='http://www.cpan.org' target='_blank'>CPAN</a> for more information.";
        goto 'ERRORS';
    }
    


    # Test for mySQL DBI::Driver
    $found = 0;
    my @drivers = DBI->available_drivers;

	foreach(@drivers){ # coolest
		if(/mysql/){
			$found = 1;
			last;
		}
	}
    unless ($found) {
        ++$errors;
        push @{ $obj->{errors} }, "You must install the mySQL DBD driver.";

    }
    
    # Test for connection
    $found = 0;
    my $dsn  = "DBI:mysql:$IN->{attr}->{'DB_NAME'}:$IN->{attr}->{'DB_IP'}";
    $dsn    .= ":$IN->{attr}->{'DB_PORT'}" if $IN->{attr}->{'DB_PORT'};

    my $dbh = DBI->connect($dsn, $IN->{attr}->{'DB_USER'}, $IN->{attr}->{'DB_PASS'});

    if ($DBI::errstr) {
        ++$errors;
        push @{ $obj->{errors} }, "mySQL connection error: $DBI::errstr";
        goto 'ERRORS';
    } 

    my $sth = $dbh->prepare("show databases");
    $sth->execute;
    while (my @log = $sth->fetchrow_array) {
    	$found = 1 if $log[0] eq $IN->{attr}->{'DB_NAME'};
    }
    unless ($found) {
        ++$errors;
        push @{ $obj->{errors} }, "mySQL cannot locate the database called $iB::IN{'DB_NAME'}.";
        goto 'ERRORS';
    }

    # Grab the create_tables.txt file and set about
    # creating our tables.

    my @SQLS;
    if ($IN->{create_tbl}) {
        local $/ = undef;
        open (MYSQL, "$IN->{schema_dir}/mysql_schema.txt") || ( push @{ $obj->{errors} }, "Cannot open the table schema!" and return );
        @SQLS = split /\;\n/, <MYSQL>;
        close (MYSQL);
  
        for my $sSQL (@SQLS) {
          next if $sSQL =~ /^\s+$/;
          if ($IN->{attr}->{'DB_PREFIX'} ne "ib_") {
            $sSQL =~ s/CREATE TABLE ib_(\w+) \(/CREATE TABLE $IN->{attr}->{'DB_PREFIX'}$1 (/ig;
          }
          $sth = $dbh->prepare($sSQL);
          $sth->execute();
          if ($DBI::errstr) {
            ++$errors;
            push @{ $obj->{errors} }, "mySQL create table error. $DBI::errstr ($sSQL)";
          }
        }
    }
    $dbh->disconnect();

    $obj->{success}++;

ERRORS:

    return;

    
}







1;
