
export LANG=zh_CN.utf8
export LC_ALL=zh_CN.utf8 2>/dev/null

#改变工作目录到当前脚本所在路径
if [[ "$0" =~ / ]]; then cd "${0%/*}"; fi

export CWD=`pwd`

if [[ -e ~/odbserver/mql ]]; then
    mqlver=`ls -l mql`
    newmqlver=`cd ~/odbserver/; ls -l mql; cd ${CWD}`
    if [[ "$mqlver" != "$newmqlver" ]]; then
        cp -pf ~/odbserver/mql mql
    fi
fi

if [[ ! -e mql.conf ]]; then
    if [[ "${ODBPATH}" = "" ]]; then
        export ODBPATH=127.0.0.1:11001
    fi
    if [[ "${KEYSPACE}" = "" ]]; then
        export KEYSPACE=oktest
    fi
fi

odbver=`./mql odbver? log.level=error "$@"`
odbpath=`./mql odbpath? log.level=error "$@"`
keyspace=`./mql keyspace? log.level=error "$@"`
if [[ `echo "${keyspace}" | wc -w` == "1" ]]; then
    logfile="${keyspace}.test.log"
    lastlogfile="${keyspace}.last.log"
else
    logfile="test.log"
    lastlogfile="last.log"
fi

if [[ "${odbpath}" != "" ]]; then
    echo ODBPATH="${odbpath}"
fi
if [[ "${keyspace}" != "" ]]; then
    echo keyspace="${keyspace}"
fi
sleep 2

filescount=`./mql files? log.level=error "$@" | wc -l`
if [[ "${filescount}" == "0" ]]; then
    ./mql "$@"
    exit $?
fi
if [[ "${filescount}" == "1" ]]; then
    n=`ps -ef | grep "mql %@" | grep -v grep | wc -l`
    n=`expr $n + 1`
    logfile="${keyspace}.${n}test.log"
    ./mql "$@" 2>&1 | tee ${logfile}
    exit $?
fi

filepath=`echo "$@" | awk '{print $NF}'`
# remove ./
filepath=${filepath/\.\//}
# remove last slash
filepath=${filepath%/}
mqlproc=`ps -ef | grep -v grep | grep mql | grep "${filepath}"`
if [[ "$mqlproc" != "" ]]; then
    echo "another mql test is running"
    exit 111
fi

if [[ -e ${logfile} ]]; then
    mv -f ${logfile} ${lastlogfile}
fi

n=`./mql keyspace=matrix - "cql:select count(*) from system_schema.columns where keyspace_name='${keyspace}' and table_name='object_test'" 2>/dev/null | grep "count" | grep -v "grep" | grep -v "select" | awk '{print $2}'`
if [[ "${n}" == "0" ]]; then
    n=1
else
    n=`cat ${keyspace}.test.count 2>/dev/null`
    n=`expr 0${n} + 1`
fi
echo "${n}" > ${keyspace}.test.count
./mql "$@" "log.prefix=test $n" 2>&1 | tee ${logfile}
lastline=`tail -n 1 $logfile 2>&1`
if [[ "$lastline" = "FAIL" ]]; then
    exit 123
elif [[ "$lastline" = "PASS" ]]; then
    echo "./mql $@" "log.prefix=test $n" 2>/dev/null >> ${keyspace}.history.log
    echo "${odbver}" 2>/dev/null >> ${keyspace}.history.log
    grep "test.code.version=" $logfile 2>/dev/null >> ${keyspace}.history.log
    tail -n 4 $logfile | head -n 1 2>/dev/null >> ${keyspace}.history.log
    exit 0
elif [[ `echo "$lastline" | grep './mqltest.sh:' | grep "已杀死"` != "" ]]; then
    exit 99
elif [[ `echo "$lastline" | grep './mqltest.sh:' | grep "killed"` != "" ]]; then
    exit 99
fi
# unkown status
exit 125
