#!/bin/bash

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

# 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=`hostname`  --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=`hostname`
../../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

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
    

    CEGOPID=`cat pid`
    kill -9 $CEGOPID
    rm cego.lock
    
    # for debugging we append 
    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
    
    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
    
    CEGOPID=`cat pid`
    kill -9 $CEGOPID
    rm -rf cego.lock

    i=$[$i+1]
    
done

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

