#!/bin/sh

printUsage()
{
    echo "Usage : $0 <numInsert>" 
}

if [ $# -lt 1 ]
then
    printUsage
    exit 1
fi

numInsert=$1

echo "################################"
echo "##### Export/Import checks #####" 
echo "################################"

./mkdb TS1

cat <<EOF >db/prepExportReady.sql
drop if exists table t1;
create table t1 ( a int, b string(30), c datetime default sysdate);

@
create procedure checkInsert ( numIns in int ) 
begin 

   var actIns int;

   :actIns = 0;

   while :actIns < :numIns
   begin
	insert into t1 (a, b) values ( :actIns , randstr(20) );	
	:actIns = :actIns + 1;
   end;

end;
@

select count(*) from t1;
call checkInsert($numInsert);
select count(*) from t1;
EOF

# cat prepExport.sql | sed "s#call checkInsert(.*)#call checkInsert($numInsert)#" > prepExportReady.sql

./runCheck TS1 local db/prepExportReady.sql quiet

echo "########### XML Export #########"

echo "Exporting database as XML ...\c"
USEDTIME=`eval "time -p $CEGO --mode=xmlexport --user=lemke/lemke --tableset=TS1 --dbxml=db/chkdb.xml --expfile=db/ts1.xml 2>&1" | grep real | sed 's/real//'`
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi
echo "Elapsed time : $USEDTIME seconds"

rm -rf db/*.sys
rm -rf db/*.temp
rm -rf db/*.dat
rm -rf db/*.log
rm -rf arch/*.dbf

echo "Recreating database ...\c"
../../src/cego --mode=create --dbxml=db/chkdb.xml --tableset=TS1
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi

echo "Importing database from XML ...\c" 
USEDTIME=`time -p ../../src/cego --mode=xmlimport --user=lemke/lemke --tableset=TS1 --dbxml=db/chkdb.xml --impfile=db/ts1.xml 2>&1 | grep real | sed 's/real//'`
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi
echo "Elapsed time : $USEDTIME seconds"

echo "########### Bin Export #########"

echo "Exporting database as binary ...\c"
USEDTIME=`time -p ../../src/cego --mode=binexport --user=lemke/lemke --tableset=TS1 --dbxml=db/chkdb.xml --expfile=db/ts1.bin 2>&1 | grep real | sed 's/real//'`
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi
echo "Elapsed time : $USEDTIME seconds"

rm -rf db/*.sys
rm -rf db/*.temp
rm -rf db/*.dat
rm -rf db/*.log
rm -rf arch/*.dbf


echo "Recreating database ...\c"
../../src/cego --mode=create --dbxml=db/chkdb.xml --tableset=TS1
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi

echo "Importing database from binary ...\c" 
USEDTIME=`time -p ../../src/cego --mode=binimport --user=lemke/lemke --tableset=TS1 --dbxml=db/chkdb.xml --impfile=db/ts1.bin 2>&1 | grep real | sed 's/real//'`
if [ $? -eq 0 ]
then
    echo " operation ok"
else
    echo " operation failed"
    exit 1
fi
echo "Elapsed time : $USEDTIME seconds"
echo "################################"
