#!/bin/ksh
#
# hack script to remigrate world

# setup directories - absolute paths
base=`pwd`
cmd=$(basename $0)
cmdBase=$(dirname $0)
cd $cmdBase
cmdBase=`pwd`
cd $base

dumpSql=$cmdBase/dumpSql

#
# create SQL
#   $1 - name of test case
#
function createSQL {

	typeset tc=$1
	typeset destDir fname

	cd $dumpSql
	rm -f core.sql domain.sql local_auth_context.sql.tmpl
	./dumpSql 0 999999999

	if [[ ! -f core.sql ]]
	then
		echo "SQL dump failed"
		exit 2
	fi

		# copy files
	destDir=$(dirname $tc)
			# save old versions
	for fname in core.sql domain.sql
	do
		if [[ ! -f $destDir/$fname.orig ]]
		then
			cp -p $destDir/$fname $destDir/$fname.orig
		fi
	done

	cp core.sql domain.sql $destDir
		# append processed local authority contexts
		#   convert md5('foo') to 'foo'
	sed -e 's/ md5(\(.*\)),/ \1,/' local_auth_context.sql.tmpl \
													>>$destDir/core.sql

	cd $base
}

#
# load the data for an individual test case
#
#	$1 - testcase path, including build.xml
function loadData {


	typeset tc=$1

	typeset buildFile=build_$$.xml
	typeset awkFile=awk_$$.awk

	cat >$buildFile  <<\EOF
<?xml version="1.0" encoding="UTF-8"?>

<!-- ******************************************************************* -->
<!-- * all: runs all test-cases                                        * --> 
<!-- ******************************************************************* -->
<project name="com.newstep.cseUnitTest.migrate" basedir="." default="all">
	<taskdef resource="net/sf/antcontrib/antlib.xml"/>
	
	<!-- load environment and preset properties -->
	<!-- your environment MUST have: -->
	<!-- 	CSE_UNITTEST_DIR	- the directory of the Cse UnitTest framework (usually ..../cse/src/BlackBox) -->
	<!-- 	CSN_DBUSER			- the user-name of the database account to use for the test --> 
	<!-- 	CSN_DBPASS			- the password of the database account to use for the test --> 
	<!-- 	CSN_DBSERVICE			- the service of the database account to use for the test --> 
	<!-- see the file called "environment" under cse/src/BlackBox/ for some examples -->
	<property environment="env"/>	
    <property name="TestCaseName" value="undefined"/>

    <!-- import the common build file -->
    <import file="${env.CSE_UNITTEST_DIR}/build-common.xml"/>
    <import file="${env.CSE_UNITTEST_DIR}/Configurations/Default.xml"/>
	
	<!-- Test Case routeCall --> 
	<!-- Setup a normal routed call -->
	<target name="run-tc" depends="" />

	<target name="setup-tc" depends="" >

        <echo> "#########################################" </echo>
        <echo> "#     Loading TC  ${TestCaseName}" </echo>
        <echo> "#########################################" </echo>
		<sql
			rdbms="${rdbms}"
    		driver="${jdbcDriver}"
    		url="${jdbcUrl}"
		    userid="${env.CSN_DBUSER}"
		    password="${env.CSN_DBPASS}"
		    autocommit="true"
		    >
		    	<!-- Clear all data -->
		    	<transaction src="${env.CSE_UNITTEST_DIR}/deleteData.sql"/>
		</sql>

		<!-- Data for this test-case 						-->

        <antcall target="Configuration.Default"/>
EOF

	# process build via awk >> $buildFile
	cat >$awkFile <<\EOF
BEGIN 			  {dumpLine = 0;}

				  {if(dumpLine == 1)
						print $0;
				  }

/<antcall target/ {dumpLine = 1;}

/<\/sql>/ 		  {dumpLine = 0;}
EOF

	awk -f $awkFile $tc >>$buildFile

	cat >>$buildFile <<\EOF
				
	</target>
</project>
EOF

	ant -f $buildFile -DTestCaseName=$(basename $(dirname $tc)) setup-tc

	rm -f $awkFile $buildFile
}

#
# scan/parse arguments
#
function scanArgs {

	if [[ $# = 0 ]]
	then
		usage
	fi

	loadOnly=0
	allSuites=0
	plugIn=''

	while getopts :alp: option
	do
		case $option in
			"a")
				allSuites=1
				;;

			"l")
				loadOnly=1
				;;

			"p")
				plugIn=$OPTARG
				;;

			"b")
				installTomcatBase=1
				;;

			"?")
				echo "$cmd: bad option ($OPTARG)"
				usage
				exit 1
				;;
		esac
	done

		# finish command scan
	shift $(($OPTIND - 1))

		# directory checks
	if [[ -z ${CSE_UNITTEST_DIR:-} ]]
	then
		echo "CSE_UNITTEST_DIR not defined"
		exit 2
	fi

	if [[ ! -d $CSE_UNITTEST_DIR ]]
	then
		echo "CSE_UNITTEST_DIR=$CSE_UNITTEST_DIR does not exist"
		exit 2
	fi

		# remove freakin' trailing / - who does this?
	UTbase=${CSE_UNITTEST_DIR%/}

		# verify suites
	if [[ $# = 0 ]]
	then
		if [[ $allSuites = 0 ]]
		then
			usage
		fi
		suiteList="$(find $UTbase -follow -name build.xml)"
	else
		if [[ $allSuites = 1 ]]
		then
			usage
		fi
		suiteList="$*"
	fi

		# verify plugin
	if [[ $loadOnly = 0 ]]
	then
		if [[ -z $plugIn ]]
		then
			usage
		else
			plugInScript=$cmdBase/plugin/$plugIn/migrate
			if [[ ! -x $plugInScript ]]
			then
				echo "Can't find plugIn script ($plugInScript)"
				exit 2
			fi
		fi
	else
		if [[ ! -z $plugIn ]]
		then
			usage
		fi
	fi

}

#
# usage
#
function usage {
	cat <<EOF
      usage: $cmd {-p plugIn | -l} {-a | test1 ...}
            -p plugIn - plugIn name to be used for conversion
            -l - load data only
            -a - process all test suites in \$CSE_UNITTEST_DIR
            test1 ... - list of test suites with respect to \$CSE_UNITTEST_DIR
EOF

	exit 1
}

#
# main starts here
#

scanArgs $@

	# redirect output

for testCase in $suiteList
do
		# skip non-test case
	if [[ $testCase = $UTbase/build.xml ]]
	then
		continue
	fi

	echo "== processing $testCase "
	if [[ ! -f $testCase ]]
	then
		testCase=$UTbase/$testCase/build.xml
		if [[ ! -f $testCase ]]
		then
			echo "Cannot find suite $(dirname $testCase)"
			continue
		fi
	fi

	if [[ $loadOnly = 0 ]]
	then
		echo "=== loading data"
		cd $(dirname $plugInScript)
		$plugInScript $testCase before
		loadData $testCase
		cd $base


		echo "=== migrate"
		cd $(dirname $plugInScript)
		$plugInScript $testCase migrate
		retCode=$?
		cd $base
		if [[ $retCode != 0 ]]
		then
			echo "migration fails; returns $retCode"
		else
			echo "=== dumpSql"
			createSQL $testCase	 
		fi

		cd $(dirname $plugInScript)
		$plugInScript $testCase after
		cd $base
	else
		echo "=== loading data"
		loadData $testCase
	fi

done

echo "== Done"


