#!/bin/bash

# range for integer value to insert, update or delete
ARANGE=1000
# amount of operations in one transaction
AINTERVAL=500
# number of operations at all
ACOUNT=200000
# check with primary btree, leave blank, if not
PRIMARY=primary
# PRIMARY=

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

# waiting max 20 seconds
MAXCRASHDELAY=15


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=2000 --tableset=TS1 --protocol=fastserial --syslog=no --lockfile=./cego.lock --cpdump --cleanup"
CGBLOW="../../src/cgblow --mode=arb2 --server=`hostname` --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"



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 count(*) from t1 order by a;
EOF

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

rm -rf cego.lock


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

    echo "### RUN $i ###"
    
    echo "Starting daemon ..."
    $CEGOUP
    
    sleep 2

    $CGCLT --batchfile=prepare.sql
    
    # Starting cgblow as a background job
    nohup $CGBLOW &


    secs=$RANDOM
    let "secs %= $MAXCRASHDELAY"

    echo "Sleeping $secs seconds .."
    sleep $secs

    # $CGCLT --batchfile=check.sql --raw > checkA 

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

    echo "Restart daemon .."
    $CEGOUP
    
    if [ $? == 1 ]
    then
	echo "Exit on Error"
	exit 1
    fi
    
    sleep 2
    
    # $CGCLT --batchfile=check.sql --raw > checkB
    

    $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 check.sql
rm post.sql

