<?
if(!function_exists("system")) {
	echo "DB Update requires php's system() function to be available\n";
	exit;
}

//include the config.inc.php
//so we have the db connection info
require("../data/config.inc.php");
require("../common.inc.php");
echo "<pre>\n";
if(file_exists("db.code.version.txt"))
{
	$dbcodeversion_file=file("db.code.version.txt");
	$dbcodeversion=trim($dbcodeversion_file[0]);
}
else
{
	echo "Couldnt load current db.code.version.txt\n";
	exit;
}

//same fix here for mysql 5.1 not truncating the 16 char usernames
$DBUSER=substr($DBUSER,0,16);


$stmt = $pdo->prepare("SET NAMES latin1");
$stmt->execute();
$q=$pdo->prepare("SELECT val FROM config WHERE var='DBVERSION' AND year='0'");
$q->execute();
$r=$q->fetch(PDO::FETCH_OBJ);
$dbdbversion=$r->val;
if(!$dbdbversion)
{
	echo "Couldnt get current db version.  Is SFIAB properly installed?\n";
	exit;
}

/* Get the fair year */
$q=$pdo->prepare("SELECT val FROM config WHERE var='FAIRYEAR' AND year='0'");
$q->execute();
$r=$q->fetch(PDO::FETCH_OBJ);
$config = array('FAIRYEAR' => $r->val);

/* Load config just in case there's a PHP script that wants it */
$q=$pdo->prepare("SELECT * FROM config WHERE year='{$config['FAIRYEAR']}'");
$q->execute();
while($r=$q->fetch(PDO::FETCH_OBJ)) $config[$r->var]=$r->val;


require_once("../config_editor.inc.php"); // For config_update_variables()

if($dbcodeversion && $dbdbversion)
{
	//lets see if they match
	if($dbcodeversion == $dbdbversion)
	{
		echo "DB and CODE are all up-to-date.  Version: $dbdbversion\n";
		exit;
	}
	else if($dbcodeversion<$dbdbversion)
	{
		echo "ERROR: dbcodeversion<dbdbversion ($dbcodeversion<$dbdbversion).  This should not happen!";
		exit;

	}
	else if($dbcodeversion>$dbdbversion)
	{
		echo "DB update requirements detected\n";
		echo "Current DB Version: $dbdbversion\n";
		echo "Current CODE Version: $dbcodeversion\n";

		echo "Updating database from $dbdbversion to $dbcodeversion\n";

		for($ver=$dbdbversion+1;$ver<=$dbcodeversion;$ver++)
		{
			if(file_exists("db.update.$ver.php"))
			{
				include("db.update.$ver.php");
			}
			if(is_callable("db_update_{$ver}_pre")) {
				echo "db.update.$ver.php::db_update_{$ver}_pre() exists - running...\n";
				call_user_func("db_update_{$ver}_pre");
				echo "db.update.$ver.php::db_update_{$ver}_pre() done.\n";
			}
			if(file_exists("db.update.$ver.sql"))
			{
				echo "db.update.$ver.sql detected - running...\n";
				readfile("db.update.$ver.sql");
				echo "\n";
				//  Dennis If 'system' and 'mysql' do not exist use each section of the sql files not system("sql" 
				//  i.e. for windows ISP servers that do not provide system and sql.exe executable
				exec("mysql -q --help", $outputnotused, $exec_sqlstatus);
				if(function_exists("system") and $exec_sqlstatus == 0 )  {
					// echo "<b><br />** db_update USING system('mysql ..) on this server!<b><br />";
					system("mysql --default-character-set=latin1 -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME <db.update.$ver.sql", $exit_code);
				}
				else{
					// Dennis  'system and 'mysql' not available on this server. loop thru all sections of .sql files
					$exit_code = 0;   // assume no errors for now
					$filename = 'db.update.'.$ver.'.sql';
					// Temporary variable, used to store current query
					$templine = '';
					// Read in entire file
					$lines = file($filename);
					// Loop through each line
					foreach ($lines as $line)
					{
						// Skip it if it's a comment
						if (substr($line, 0, 2) == '--' || $line == '')
							continue;
 						// Add this line to the current segment
						$templine .= $line;
						// If it has a semicolon at the end, it's the end of the query
						if (substr(trim($line), -1, 1) == ';')
						{
							// Perform the query
							if(!$pdo->query($templine)){
								echo('<br/>Error performing query!<br/>'.$templine.'<br/>  mysqlerror: '.$pdo->errorInfo().'<br /><br />');
								$error_count += 1;
							    $exit_code = -1;   // do we bail out here or keep going?  keep going for now,  get all errors
							}
							// Reset temp variable to empty
							$templine = '';
						}
					}
					echo "<br />";				
				}
				if($exit_code != 0) {
					/* mysql failed!, what now? */
					$error_count += 1;
		        	echo "<br /><b>ERROR in db_update: Failed to execute query(s) without error!<br />";
					echo "Update scripts bad or system('mysql' .. ) call failed!</b><br /><br />";
				}
			}
			else
			{
				echo "Version $ver SQL update file not found - skipping over\n";
			}
			if(is_callable("db_update_{$ver}_post")) {
				echo "db.update.$ver.php::db_update_{$ver}_post() exists - running...\n";
				call_user_func("db_update_{$ver}_post");
				echo "db.update.$ver.php::db_update_{$ver}_post() done.\n";
			}
		}
		if($db_update_skip_variables != true) {
			echo "\nUpdating Configuration Variables...\n";
			config_update_variables($config['FAIRYEAR']);
		}

		echo "\nAll done - updating new DB version to $dbcodeversion\n";
		$stmt = $pdo->prepare("UPDATE config SET val='$dbcodeversion' WHERE var='DBVERSION' AND year='0'");
		$stmt->execute();
	}

}
else
{
	echo "ERROR: dbcodeversion and dbdbversion are not defined\n";
}

echo "</pre>\n";

?>