#!/usr/bin/env bash
if [ $# -lt 1 ] ; then
    echo "usage: $(basename $0) PROPS_FILE" >&2
    exit 2
fi
function prepare()
{
        ip=$(cat $*|sed -n '/conn=/ p'|awk -F'[:/]' '{print $5}')
        user=$(cat $*|sed -n '/user=/ p'|awk -F'[=]' '{print $2}')
        password=$(cat $*|sed -n '/password=/ p'|awk -F'[=]' '{print $2}')
        profile=$(cat $*|sed -n '/profile=/ p'|awk -F'[=]' '{print $2}')
        data=$(cat $*|sed -n '/data=/ p'|awk -F'[=]' '{print $2}')
        backup=$(cat $*|sed -n '/backup=/ p'|awk -F'[=]' '{print $2}')
        ssh root@${ip} "su - mysql -c 'mysqladmin --defaults-file=${profile} -u ${user} --password='${password}' shutdown'"
        ssh root@${ip} sysctl vm.drop_caches=3
        ssh root@${ip} "su - mysql -c 'rm -rf ${data} && cp -r ${backup} ${data}'"
        timeout 10 ssh root@${ip} "su - mysql -c 'mysqld_safe --defaults-file=${profile}'"
}

if [ "$2" != "" ];then
prepare $1
fi

SEQ_FILE="./.jTPCC_run_seq.dat"
if [ ! -f "${SEQ_FILE}" ] ; then
    echo "0" > "${SEQ_FILE}"
fi
SEQ=$(expr $(cat "${SEQ_FILE}") + 1) || exit 1
echo "${SEQ}" > "${SEQ_FILE}"

source funcs.sh $1

setCP || exit 1

myOPTS="-Dprop=$1 -DrunID=${SEQ}"

echo "`date` -- warmup"
timeout 60 java -cp "$myCP" $myOPTS jTPCC
echo "`date` -- start test"
java -cp "$myCP" $myOPTS jTPCC