<?
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;
}

if(file_exists("db.db.version.txt"))
{
	$dbdbversion_file=file("db.db.version.txt");
	$dbdbversion=trim($dbdbversion_file[0]);
}
else
{
	echo "Couldnt load current db.db.version.txt - assuming version is 1\n";
	$dbdbversion=1;
}

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!";

	}
	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";
		//include the config.inc.php
		//so we have the db connection info
		require("../config.inc.php");

		for($ver=$dbdbversion+1;$ver<=$dbcodeversion;$ver++)
		{
			if(file_exists("db.update.$ver.sql"))
			{
				echo "db.update.$ver.sql detected - running...\n";
				readfile("db.update.$ver.sql");
				echo "\n";
				system("mysql -h$DBHOST -u$DBUSER -p$DBPASS $DBNAME <db.update.$ver.sql");
			}
			else
			{
				echo "Version $ver update file not found - skipping over\n";
			}
		}
		echo "\nAll done - updating new DB version to $dbcodeversion\n";
		$fp=fopen("db.db.version.txt","w");
		fputs($fp,$dbcodeversion."\n");
		fclose($fp);
	}

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


?>