#!/bin/env bash
##Description: run sqlfile or sql stmt

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "ksh ${ShellName}  [-clsname <clsname>] [-hostname <hostname>]"
    echo "  [-ip <ip>] [-port <port>] [-user <user>] [-passwd <passwd>]  "
    echo "  [-stmt <select ...>] "
    echo "  [-sqlfile <select.txt>] "
    echo "  [-check]"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -clsname sa2 -IP 172.16.xxx -port 4100 -user abcuser1 -passwd xxx -sqlstmt select * from  -sqlfile 1.sql"
    echo " #sh ${ShellName} -clsname sa2 -IP 172.16.xxx -port 4100 -user abcuser1 -passwd xxx -sqlfile 1.sql"
    exit 22
}

function f_PrintLog
{
    _LogFlag=$(echo "$1"|tr "a-z" "A-Z")
    [ $(echo "$1"|wc -L) -eq 4 ] && _LogFlag=$(echo "${_LogFlag}_")
    _LogMessage=$2
    declare LogFile="${LogFile:-"/tmp/${PShellName:-${ShellName}}.log"}"
    touch "${LogFile}" 2>/dev/null
    if [ -w "${LogFile}" ]
    then
        echo "$(date "+%Y%m%d.%H%M%S"):[${_LogFlag}]:${UserName}@${HostName}:${2}"|tee -a "${LogFile}";
    else
        echo "$(date "+%Y%m%d.%H%M%S"):[${_LogFlag}]:${UserName}@${HostName}:${2}";
    fi
}


###############################################################################
##Init##
ShellName="$(echo $0|awk -F / '{print $NF}')";ShellOption="$@";
WorkDir="$(echo $0|sed s/${ShellName}//g)";[ -z "${WorkDir}" ] && WorkDir=${PWD};cd ${WorkDir};WorkDir=${PWD}
LogDir="${WorkDir%/}/logs";mkdir -p ${LogDir};chmod ugo+rwx ${LogDir} 2>/dev/null
LogFile="${LogDir}/${ShellName}.$(date "+%Y%m%d.%H%M%S").log";LogLevel=3;
touch "${LogFile}" 2>/dev/null;chmod ugo+rw "${LogFile}" 2>/dev/null
declare Shellcksum=$(cksum ${WorkDir%/}/${ShellName} 2>/dev/null|awk '{printf "%d",$1}')
declare -i UserID=$(id -u);declare UserName=$(whoami);declare HostName=$(hostname);
###############################################################################
##Get inopt
[ -z "${ShellOption}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -HOSTNAME|-HOST) CurOpt="-HOSTNAME";continue;;
    -CLSNAME|-C) CurOpt="-CLSNAME";continue;;
    -IP) CurOpt="-IP";continue;;
    -PORT) CurOpt="-PORT";continue;;
    -USER|-U) CurOpt="-USER";continue;;
    -PASSWORD|-PASSWD) CurOpt="-PASSWORD";continue;;
    -SQLFILE|-F) CurOpt="-SQLFILE";continue;;
    -SQLSTMT|-S) CurOpt="-SQLSTMT";continue;;
    -CHECK|--CHECK) CurOpt="-CHECK";declare CHECK="YES";continue;;
    -FORCE|--FORCE) CurOpt="-FORCE";declare FORCE="FORCE";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME) declare LocalHost="${inopt}";continue;;
    -CLSNAME) declare clsname="${inopt}";continue;;
    -IP) declare tidbip="${inopt}";continue;;
    -PORT) declare tidbport="${inopt}";continue;;
    -USER) declare tidbuser="${inopt}";continue;;
    -PASSWORD) declare tidbpasswd="${inopt}";continue;;
    -SQLFILE) declare sqlfile="${inopt}";continue;;
    -SQLSTMT) declare sqlstmt=$(echo "${sqlstmt} ${inopt}");continue;;
    esac
done

f_PrintLog "Info" "Start to run Script ${ShellName}, the Shellcksum is ${Shellcksum}"
f_PrintLog "Debug" "Script Options:${ShellOption}"

function f_runsqlfile
{
    _sqlfile=$1

    f_PrintLog "Info" "START TO RUN SQL FILE:${_sqlfile}"
    echo "*************************************************************"
    cat ${_sqlfile}
    echo "*************************************************************"
    f_PrintLog "Info" "PLS CHECK ALL COMMANDS IN FILE, SLEEP 10......"
    sleep 1
    echo "mysql -h${tidbip} -P${tidbport} -u${tidbuser} -p${tidbpasswd:-123} -vvv < ${_sqlfile}"
    if [ "${CHECK:-1}" = "YES" ] 
    then 
        f_PrintLog "Info" "check=yes ,Just Check command ......"
        return 0
    fi
    mysql -h${tidbip} -P${tidbport} -u${tidbuser} -p${tidbpasswd:-123} -vvv < ${_sqlfile}
    return $?
}


function f_runsqlstmt
{
    _sqlstmt=$1

    f_PrintLog "Info" "START TO RUN SQL STMT:${_sqlstmt}"
    echo "*************************************************************"
    echo ${_sqlstmt}
    echo "*************************************************************"
    f_PrintLog "Info" "PLS CHECK SQL STMT, SLEEP 10......"
    sleep 1
    echo "mysql -h${tidbip} -P${tidbport} -u${tidbuser} -p${tidbpasswd:-123} -vvv -e ${_sqlstmt}"
    mysql -h${tidbip} -P${tidbport} -u${tidbuser} -p${tidbpasswd:-123} -vvv -e "${_sqlstmt}"
    return $?
}



###################
####    Main   ####
###################

#1. 执行SQL文件
#2. 执行SQL语句

#check parameter
if [ -z "${sqlfile}" -a -z "${sqlstmt}" ]
then
    f_PrintLog "Error" "Pls provide the sql file or stmt!"
    f_syntax
fi

#run sqlfile
if [ -n "${sqlfile}" -a -f "${sqlfile}" ] 
then
    f_runsqlfile ${sqlfile}
    _rt_code=$?
    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "run sql file ${sqlfile} finish!"
    else
        f_PrintLog "Error" "run sql file ${sqlfile}  failed!!!"
        exit 1
    fi
elif [ -n "${sqlfile}" -a ! -f ${sqlfile} ]
then
    f_PrintLog "Error" "sql file ${sqlfile} not exist,pls check !!!"
    exit 1
fi


#run sqlstmt
if [ -n "${sqlstmt}" ] 
then
    f_runsqlstmt "${sqlstmt}"
    _rt_code=$?
        if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "run sql stmt ${sqlstmt} finish!"
    else
        f_PrintLog "Error" "run sql stmt ${sqlstmt}  failed!!!"
        exit 1
    fi
fi

