#!/usr/bin/php
<?php
/*
Copyright (c) 2010, Justin Swanhart
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*This script requires PEAR Net_Gearman */
/*It also requires Console_Getopt, but this should be installed by default with pear */
set_include_path(get_include_path() . PATH_SEPARATOR . '../include');
require_once 'Console/Getopt.php';
require_once 'shard-query.php';
require_once 'common.php';
require_once 'testmore.php';
$SQ = new ShardQuery();
$RECORD_MODE = false;

$verbose=false;

main();
exit;

#this is a Shard-Query stub for recording
#results from a real database
class SQ_stub {
	var $errors = array();
	function __construct($schema='test', $config_file=null) {
		$info = array(
			'host'=>'127.0.0.1',
			'port'=>3306, 
			'user'=>'root', 
			'password'=>'toor', 
			'db'=>$schema, 
			'type'=>'mysql'
		);
		$this->DAL = SimpleDAL::factory($info);
		$this->DAL->my_select_db($schema);
	}

	function query($sql) {
		return $this->DAL->my_query($sql);
	}
}

function help() {
	shard_query_common_help();
	run_query_help();
	echo "\n";
	exit;
}

/* Like ok() in test::more but tests SQL 
   results against the stored result, or
   records results from a real database.
*/
function sql_ok($sql, $test_name) {
	global $RECORD_MODE;
	global $SQ;
	global $SUITE_NAME;

	#make sure that identically named tests in the same
	#suite record different result filenames
	static $state = array();
	if(empty($state[$SUITE_NAME])) $state[$SUITE_NAME] = 0;
	++$state[$SUITE_NAME];

	$r = 'r/' . $SUITE_NAME . "." .  md5($test_name . $sql . $state[$SUITE_NAME]) . '.result';

	$stmt = $SQ->query($sql);
	if(is_resource($stmt)) {
		$rows = array();
		while($row = $SQ->DAL->my_fetch_assoc($stmt)) $rows[] = $row;
		$result = serialize($rows);
	} else {
		$result = $stmt;
	}

	if($RECORD_MODE == true) {
		file_put_contents($r, $result);
		return pass($test_name);
	}
	if(!file_exists($r)) {
		fail($test_name);
		diag('Failure reason: result file is missing!');
		return false;
	}

	$expected = file_get_contents($r);
	if($result !== $expected) { 
		fail($test_name);
		echo "EXPECT: $expected\nRESULT: $result\n";
		if(!empty($SQ->errors)) { echo "SQ ERRORS:\n " . print_r($SQ->errors, true) . "\n"; }
		return false;
	}

	return pass($test_name);
}


function new_connection() {
	global $RECORD_MODE;
	global $SQ;

	if($RECORD_MODE == true) {
		$SQ = new SQ_stub();
	} else {
		$SQ = new ShardQuery();
	}
	return($SQ->DAL); 
}

function main() {
	$params = get_commandline(array('tests==', 'record'));
	global $SQ;
	global $RECORD_MODE;
	global $SUITE_NAME;

	if(has_short_opt('help',$params)) help();
	$RECORD_MODE = has_short_opt('record', $params);
	if($RECORD_MODE === true) 
		diag("RECORDING HAS BEEN ENABLED: SHARD-QUERY OBJECTS ARE STUBBED!\n");

	#run the tests requested by the user
	if(!empty($params['tests'])) {
		$tests = explode(',', $params['tests']);
	} else {
		#or run all tests
		$tests = glob("t_*");
	}

	echo "Going to run: " . join(",", $tests) . "\n";

	foreach($tests as $SUITE_NAME) {
		#provide a new global SQ object to the test
		new_connection();
		echo "Running $SUITE_NAME\n";
		require($SUITE_NAME);
	}

	echo "test suite completed.\n";
}
