#!/bin/bash

# how many crash/recoveries shoud be done
NUMRUN=50

# transaction switch, leave blank for atomic mode
DOTRANSACTION=-dotransaction
# DOTRANSACTION=

# range for integer value to insert, update or delete
ARANGE=10000
# amount of operations in one transaction ( just relevant for enabled transaction mode )
AINTERVAL=500
# number of operations at all
ACOUNT=30000
# check with primary btree, leave blank, if not
PRIMARY=primary
# PRIMARY=

# POOLSIZE=5011
POOLSIZE=191

############ end of customizing ############


CGCLT="../../src/cgclt --server=localhost  --port=2200 --tableset=TS1 --user=lemke/lemke --logfile=clt.log --protocol=fastserial --maxresult=1000000 --ignore $@"
CEGOUP="../../src/cego --mode=daemon --forceload --numdbthread=20 --dbxml=./db/chkdb.xml --poolsize=$POOLSIZE --tableset=TS1 --protocol=fastserial --syslog=no --lockfile=./cego.lock --cleanup"

cat <<EOF > prepare.sql
drop if exists table t1;
create table t1 ( $PRIMARY a int not null, b string(50));
EOF

cat <<EOF > check.sql
select a,b from t1 order by a;
EOF

cat <<EOF > post.sql
show systemspace;
EOF

cat <<EOF > arbblow
#!/bin/bash
DBHOST=localhost
../../src/cgblow --mode=arb2 --server=$DBHOST --port=2200 --table=t1 --tableset=TS1 --user=lemke/lemke --interval=$AINTERVAL --count=$ACOUNT --protocol=fastserial \
--iset=i:$ARANGE,s:2 --uset=b:s:2 --ucond=a:i:$ARANGE --dcond=a:i:$ARANGE --append $DOTRANSACTION --simulate $@
EOF

chmod 755 arbblow

rm -rf cego.lock
rm -rf crashcheck.log

i=1
while [ $i -lt $NUMRUN ] 
do

    echo "Creating database ..."
    ./mkdb TS1
    
    echo "Starting daemon ..."
    rm -rf daemon.out
    $CEGOUP > daemon.out

    while [ "`cat daemon.out | grep 'up and running'`" = "" ]
    do
	echo "Waiting for daemon ..."
	sleep 2
    done
    
    # use already created arb.sql
    ./arbblow > arb.sql

    $CGCLT --batchfile=prepare.sql
    $CGCLT --batchfile=arb.sql > /dev/null
    $CGCLT --batchfile=check.sql --raw > checkA 
    # ./chkadm --batchfile=ta.batch
    
    echo "Killing daemon process ..."
    CEGOPID=`cat pid`
    kill -9 $CEGOPID
    rm cego.lock
    
    # for debugging we append 
    echo "Restarting daemon ..."
    rm -rf daemon.out
    $CEGOUP >> daemon.out
    
    while [ "`cat daemon.out | grep 'up and running'`" = "" ]
    do
	echo "Waiting for daemon ..."
	sleep 2
    done
    
    if [ $? == 1 ]
    then
	echo "Exit on Error"
	exit 1
    fi
    
    sleep 2
    
    $CGCLT --batchfile=check.sql --raw > checkB
    
    echo "Compare checkA and checkB"
    if [ "`diff -c checkA checkB`" ]
    then
	echo "Run $i : Diff detected" >> crashcheck.log
	echo "Exit on Diff"
	exit 1
    else
	echo "Run $i : OK" >> crashcheck.log
    fi

    $CGCLT --batchfile=post.sql


    echo "Killing daemon process finally ..."
    CEGOPID=`cat pid`
    kill -9 $CEGOPID
    rm -rf cego.lock

    sleep 2
    
    i=$[$i+1]
    
done

# cleanup generated files
rm prepare.sql
rm arb.sql
rm check.sql
rm post.sql
rm arbblow

