#!/bin/env bash
##Description: precheck before tidb dr swtich over 

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "ksh ${ShellName}  [-hostname <hostname>]"
    echo "  [-ip <ip>] [-port <port>] [-user <user>] [-passwd <passwd>]  "
    echo "  [-ignoreusers <user1 user2 user3>] "
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -ip 172.16.4.xxx -port 4100 -user abcuser1 -passwd saxxx -ignoreusers root"
    exit 22
}

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


###############################################################################
##Init##
ShellName="$(echo $0|awk -F / '{print $NF}')";ShellOption="$@";
ShellPID=$$;PShellName=$(echo "${ShellName}"|sed 's/^[0-9]*_//');
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;;
    -IGNOREUSERS|-I) CurOpt="-IGNOREUSERS";continue;;
    -IP) CurOpt="-IP";continue;;
    -PORT) CurOpt="-PORT";continue;;
    -USER|-U) CurOpt="-USER";continue;;
    -PASSWORD|-PASSWD) CurOpt="-PASSWORD";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME) declare LocalHost="${inopt}";continue;;
    -IGNOREUSERS) declare ignoreusers=$(echo "${ignoreusers} ${inopt}");continue;;
    -IP) declare tidbip="${inopt}";continue;;
    -PORT) declare tidbport="${inopt}";continue;;
    -USER|-U) declare tidbuser="${inopt}";continue;;
    -PASSWORD|-P) declare tidbpasswd="${inopt}";continue;;
    esac
done

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

function f_checkapplication
{
    set -e
    f_PrintLog "Debug" "Start to run f_checkapp."
    f_PrintLog "Info" "Check process privileges, current user:${tidbuser}!"
    mysql -u${tidbuser} -p${tidbpasswd} -h${tidbip} -P${tidbport} -vvv -e "show grants for ${tidbuser}"
    f_PrintLog "Info" "Start to check applications, ignoreusers:${ignoreusers}!!"
    mysql -u${tidbuser} -p${tidbpasswd} -h${tidbip} -P${tidbport} -vvv -e "select user,count(1),group_concat(id SEPARATOR ',') from information_schema.cluster_processlist group by user"
    mysql -u${tidbuser} -p${tidbpasswd} -h${tidbip} -P${tidbport} -NBe "select user,count(1),group_concat(id SEPARATOR ',') from information_schema.cluster_processlist group by user;" | while read username appcount appid
    do
        if [ -z "$(echo ${ignoreusers} | grep -w ${username})" ]
        then
            f_PrintLog "Warn" "find application in database, user:${username} appcount:${appcount}, pls stop or kill these applications!!!"
            echo "${username} ${appid}" >> ${tmp_file}
        else
            f_PrintLog "Info" "find application in database, user:${username} appcount:${appcount}, ignore these applications!"
        fi
    done
}


###################
####    Main   ####
###################
#ignore user list 
# if [ ! -z "$(echo ${ignoreusers} | grep ,)" ]
# then
#     f_PrintLog "Info" "Start to format input variables, ignoreusers:${ignoreusers}!"
#     declare T_IFS="${IFS}";declare IFS=",";
#     for u in ${ignoreusers}
#     do
#         ignoreusers_new=$(echo ${ignoreusers_new} ${u%%@*})
#     done
#     declare IFS="${T_IFS}"
#     ignoreusers=${ignoreusers_new}
#     f_PrintLog "Info" "Start to format input variables, ignoreusers:${ignoreusers}!"
# fi

tmp_file="./logs/tmp_apps.txt"
echo "" > ${tmp_file}

f_checkapplication

app_counts=$(wc ${tmp_file}|awk '{printf "%d",$1+$2}')
if [ ${app_counts} -gt 1 ]
then
    f_PrintLog "Error" "some applications still use database, pls check file ${tmp_file} !!!"
    exit 1
else
    f_PrintLog "Info" "all applications are closed, check pass!"
    exit 0
fi

