#!/bin/sh

# sysbench.common

#dbtype=mysql
dbtype=pgsql

tablesize="100000"

pg_ctl -D /home/mikeg/postgres -l logfile start
sleep 5

case $dbtype in
    mysql)
        connect="--mysql-host=127.0.0.1 --mysql-port=3306 --mysql-db=sbtest --mysql-user=mikeg"
        common="--test=oltp --db-driver=mysql --oltp-table-size=${tablesize}"
        ;;
    pgsql)
#        connect="--pgsql-host=127.0.0.1 --pgsql-port=5432 --pgsql-db=sbtest --pgsql-user=mikeg"
        connect="--pgsql-host="" --pgsql-db=sbtest --pgsql-user=mikeg"
        common="--test=oltp --db-driver=pgsql --oltp-table-size=${tablesize}"
        ;;
    *)
        echo "Unknown dbtype";
        exit 1;
        ;;
esac


# sysbench.prepare

# dropdb sbtest
# createdb sbtest

# cmd="sysbench ${common} ${connect} prepare"
# echo $cmd
# $cmd

# systench.test

steps="1 1 2 4 8 16 32 64 128"
requests="10000"
# system setup
# - fbsd7-ufs, fbsd7-zfs
# - linux26-cdb2
#flavor="linux26-mysql5041-tcmalloc"
#flavor="linux26-mysql5041"
#flavor="fbsd7-zfs-8k"
#flavor="fbsd7-ufs-pgsql-skiptxn"
#flavor="fbsd7-zfs-pgsql-4BSD"
# flavor="fbsd7-zfs-pgsql-4BSD-nosync"
flavor=`uname -r`-pgsql
#flavor="fbsd7-ufs-4BSD"
# test type, ro/rw
testtype="ro"
# resultdir
resultdir='/home/mikeg/results/'
# args
args="${common} ${connect} --max-time=60 --max-requests=0 --oltp-test-mode=complex --oltp-dist-iter=16"

case ${testtype} in
    ro)
        args="${args} --oltp-read-only=on --oltp-skip-trx=off"
        ;;
    rw)
#        test ${dbtype} = "mysql" && args="${args} --oltp-skip-trx=on"
        args="${args} --oltp-read-only=off --oltp-skip-trx=off"
        ;;
esac

resultfile() {
    local threads=$1
    echo ${resultdir}/${flavor}.${testtype}.${threads}
}
plotdata=`echo ${resultdir}/${flavor}.${testtype}.plot | tr '.-' _`

rm -f ${plotdata}
rm -f ${resultdir}/${flavor}.${testtype}.*

#cmd="sysbench --num-threads=16  ${args} run"
#echo $cmd
#$cmd
#exit

echo -n > ${plotdata}

for threads in ${steps}
do
    cmd="sysbench --num-threads=${threads} ${args} run"
    out=`resultfile ${threads}`
    echo ${cmd} > ${out}
    echo "Testing with ${threads}"
    success=0
    while test ${success} -eq 0;
    do
        date
        date >> ${out}
        $cmd >> ${out} && success=1
        test ${success} -eq 0 && (echo "Test failed, restarting")
    done
    cat ${out}
    awk '/read.write requests/ {sub("^.", "", $4); print $4}' ${out} >> ${plotdata}
done

pg_ctl -D /home/mikeg/postgres -l logfile stop
