<?php

if(!is_dir('interface') && !is_dir('sql')) die('Please enter the install sirectory before you execute the update.php script.'); 

// Copy the files
exec('chown -R ispconfig:ispconfig interface');
exec('cp -rf interface /usr/local/ispconfig');
exec('chmod 770 /usr/local/ispconfig/interface/invoices');
exec('chown ispconfig:ispconfig /usr/local/ispconfig/interface/invoices');

//* Load ispconfig settings
include_once('/usr/local/ispconfig/server/lib/config.inc.php');
include_once("/usr/local/ispconfig/server/lib/mysql_clientdb.conf");

//* Check billing module version
if(substr(ISPC_APP_VERSION,0,5) != '3.0.4') die('This ISPConfig Billing Module version requires ISPConfig 3.0.4.');
if(!is_dir('/usr/local/ispconfig/interface/web/billing')) die('No ISPCOnfig Billing module installation found.');

//* Create database conection (ispconfig user, not root).
include_once('sql/lib/mysql.lib.php');
$db = new db();
$force_db_update = false;

$tmp = $db->queryOneRecord("SELECT revnum FROM invoice_settings WHERE invoice_settings_id = 1");
$current_db_version = $tmp['revnum'];
unset($tmp);

//* Fix for database scheme update problem rev-1 to rev-2, force update again
if($current_db_version == 2) {
	$current_db_version = 1;
	$force_db_update = true;
}

/*
$clientdb_host                  = 'localhost';
$clientdb_user                  = 'root';
$clientdb_password              = 'xxxxx';
*/

//* Load the changes into the database
$found = true;
while($found == true) {
	$next_db_version = intval($current_db_version + 1);
	$patch_filename = realpath(dirname(__FILE__)).'/sql/incremental/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.sql';
	if(is_file($patch_filename)) {
		//* Load patch file into database
		if( !empty($clientdb_password) ) {
			$cmd = "mysql --default-character-set=".$conf['db_charset']." --force -h '".$clientdb_host."' -u '".$clientdb_user."' -p'".$clientdb_password."' ".$conf['db_database']." < ".$patch_filename;
			if($force_db_update == true) $cmd .= ' > /dev/null 2> /dev/null';
			system($cmd);
		}
		echo 'Loading SQL patch file'.': '.$patch_filename."\n";
		$current_db_version = $next_db_version;
	} else {
		$found = false;
	}
}
		
//* update the database version in server table
$db->query("UPDATE invoice_settings SET revnum = '".$current_db_version."' WHERE WHERE invoice_settings_id = 1");

echo "ISPConfig Billing module has been updated.\n";

?>