#!/bin/env bash
##Description: generate switch config and exec precheck

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "bash ${ShellName}  [-primaryhostname <hostname>]"
    echo "-standbyhostname <hostname_standby> "
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -hostname node1 -standbyhostname sa-172-16-4-81" 
    echo " "
    exit 22
}

function f_PrintLog
{
    _LogFlag=$(echo "$1"|tr "a-z" "A-Z")
    _LogMessage=$2
    [ $(echo "$1"|wc -L) -eq 4 ] && _LogFlag=$(echo "${_LogFlag}_")
    echo "$(date "+%Y%m%d.%H%M%S"):[${_LogFlag}]:${UserName}@${HostName}:${2}";
}

###############################################################################
function f_checkusedtool
{
    f_PrintLog "Info" "Start to run f_checkusedtool."
    binary_list="$1"
    f_PrintLog "Info" "Start to check command: ${binary_list}"
    total_fail=0
    total_cmd=0
    for bin_cmd in $(echo ${binary_list})
    do 
        _rt=$(which ${bin_cmd} 2>/dev/null)
        cmd_ok=$?
        if [ ${cmd_ok} -eq 0 ]
        then
            f_PrintLog "Info" "command ${bin_cmd} was installed on ${_rt}."
        else
            f_PrintLog "Warn" "command ${bin_cmd} was not installed. ${_rt}"
            total_fail=$(($total_fail+1))
        fi
        total_cmd=$(($total_cmd+1))
    done
    [ ${total_fail} -gt 0 ] && _flag="Error" || _flag="Info"
    f_PrintLog "${_flag:-INFO}" "check command failed, fail/total num is ${total_fail}/${total_cmd}"
}

function f_checktidb
{

    f_PrintLog "Info" "Start to run f_checktidb."

    #tidb status
    f_PrintLog "Info" "the Up node list:" 
    echo "${tidbclsinfo}"|awk '{
        if(NF>=8 && $2~"[pd|ti|pr|pu|dr|pr]" && $6~"Up"){printf "%20s %15s %10s\n",$1,$2,$6}
        }'
    
    f_PrintLog "Warn" "the Down node list:" 
    echo "${tidbclsinfo}"|awk '{
        if(NF>=8 && $2~"[pd|ti|pr|pu|dr|pr]" && $6!~"Up"){printf "%20s %15s %10s\n",$1,$2,$6}
        }'

    # drainer_down=$(echo "${tidbclsinfo}" | awk -F: '{
    #     if($1~"binlog_status" && $2!~"On"){gsub("[, ]","",$2);gsub("\"","",$2);printf "%s",$2;exit}
    # }')
    drainer_status=$(tiup cluster display ${clsName}  2>/dev/null |awk -v dip="${tidbDrainerId}" '{
        if($1==dip && $2=="drainer"){printf "%s",$6;exit}
        }')
    
    if [ -z "$(echo "${drainer_status:-Up}" | grep -E "Up|Down")" ]
    then
        f_PrintLog "Error" "drainer status check failed. drainer status is ${tidbDrainerId}:${drainer_status}"
        exit 1
    else
        f_PrintLog "Info" "drainer status is ok."
    fi
}

function f_checktidbbinlog
{
    binlog_url=$1

    f_PrintLog "Info" "Start to run f_checktidbbinlog"
    # binlogstatus=$(curl "http://${binlog_url}/info/all")
    # f_formatjson ${binlogstatus}
    binlog_down=$(curl -s "http://${binlog_url}/info/all" | awk -F: '{
        if($1~"binlog_status" && $2!~"On"){gsub("[, ]","",$2);gsub("\"","",$2);printf "%s",$2;exit}
    }')

    binlog_up=$(curl -s "http://${binlog_url}/info/all" | awk -F: '{
        if($1~"binlog_status" && $2~"On"){gsub("[, ]","",$2);gsub("\"","",$2);printf "%s",$2;exit}
    }')
    
    curl -s "http://${binlog_url}/info/all" | awk -F: '
    /^[ "]*ip.*/{gsub("[, ]","",$2);gsub("\"","",$2);ip=$2}
    /^[ "]*listening_port.*/{gsub("[, ]","",$2);gsub("\"","",$2);port=$2}
    /^[ "]*binlog_status.*/{gsub("[, ]","",$2);gsub("\"","",$2);binlog=$2}
    /^[ "]*server_id.*/{TiDB[$2]=tidb;IP[$2]=ip;Port[$2]=port;Binlog[$2]=binlog;}
    END{for(a in TiDB){printf "binlog_status: %s:%s %s\n",IP[a],Port[a],Binlog[a]}}
    '

    if [ "${binlog_down:-On}" = "On" -a "${binlog_up:-Off}" = "On" ]
    then
        f_PrintLog "Info" "binlog_status is ok."
    else
        f_PrintLog "Error" "binlog_status check failed. binlog_status is ${binlog_up}:${binlog_down}"
        exit 1
    fi
}

function f_checkconnection
{
    _ip=$1

    f_PrintLog "Debug" "Start to run f_checkconnection."
    # f_PrintLog "Info" "Check process privileges, current user:${tidbuser}!"
    # mysql -u${user} -p${passwd} -h${ip} -P${port} -vvv -e "show grants for ${tidbuser}"
    ignoreusers=${adminusers}
    f_PrintLog "Info" "Start to check applications, ignoreusers:${ignoreusers}!!"
    mysql -u${user} -p${tidbPasswd:-123} -h${_ip} -P${tidbPort} -vvv -e "select user,count(1) from information_schema.cluster_processlist group by user"
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "failed to run processlist query, pls check!!!"
        exit 1
    fi
    mysql -u${user} -p${tidbPasswd:-123} -h${_ip} -P${tidbPort} -NBe "select user,count(1) from information_schema.cluster_processlist group by user;" | while read username appcount
    do
        if [ -z "$(echo ${ignoreusers} | grep -w ${username})" ]
        then
            f_PrintLog "Error" "find connections in database, user:${username} appcount:${appcount}, pls stop or kill these connections!!!"
            echo "${username} ${appcount}" >> ${tmp_file}
        else
            f_PrintLog "Info" "find connections in database, user:${username} appcount:${appcount}, ignore these connections!"
        fi
    done
}

function f_runsqlstmt
{
    _ip=$1
    _port=$2
    _user=$3
    _passwd=$4
    _execsql=$5

    f_PrintLog "Info" "START TO RUN SQL STMT:${_execsql}, DBinfo ${_ip}:${_port}"
    mysql -h${_ip} -P${_port} -u${_user} -p${_passwd:-123} -vvv -e "${_execsql}"
    return $?
}

function f_check_insert
{
    _ip=$1
    _ip_s=$2

    #insert into primary, check standby replicate
    f_PrintLog "Info" "Start to run f_check_insert."
    f_PrintLog "Info" "Start to insert ${_ip} -> ${_ip_s}."

    #sql
    tmp_table="test.drainer_delay"
    create_tab="create table If Not Exists ${tmp_table}(ts datetime)"
    delete_tab="delete from ${tmp_table}"
    insert_tab="insert into ${tmp_table}(ts) values(now(0))"
    select_tab="select max(ts) from ${tmp_table}"
    #
    
    #Primary
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${create_tab}"
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${delete_tab}"
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${insert_tab}"
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${select_tab}"

    
    p_val=$(mysql -h${_ip} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${select_tab}")
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "exec sql failed, stmt: ${select_tab}"
    fi
    
    sleep 1
    #Standby
    # f_PrintLog "Info" "START TO RUN SQL STMT:${select_tab}, DBinfo ${s_ip}:${s_port} "
    f_runsqlstmt "${_ip_s}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${select_tab}"
    for i in 1 2 3
    do
        f_runsqlstmt "${_ip_s}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${select_tab}"
        s_val=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${select_tab}")
        if [ "${s_val:-0}" = "${p_val:-1}" ]
        then
            # break
            f_PrintLog "Info" "Real time Data replicate successful: ${p_val}=${s_val}, check pass! "
            f_PrintLog "Succ" "Tmp table insert and replicate successful, drainer working good!"
            return 0
        fi
        f_PrintLog "Warn" "Real time Data replicate failed: ${p_val}!=${s_val}, continue ${i} !!! "
        sleep 3
    done

    f_PrintLog "Error" "Real time data replicate:${p_val}!=${s_val}, check failed!!!"
    f_PrintLog "Error" "Tmp table insert and replicate failed, pls check data in ${tmp_table} !!!"
    exit 1
}

function f_tsmap_stable
{
    _ip_s=$1

    #获取checkpoint表中的tsmap信息
    f_PrintLog "Info" "Start to run f_tsmap_stable."
    #tsmap
    ck_sql="select checkPoint from ${checkpointschema}.checkpoint order by clusterID desc limit 1"
    f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip_s}:${tidbPort}"
    exec_result=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
    tsmap_tso=$(echo $exec_result  | python -m json.tool | awk '{if($0~"ry-ts"){printf "%s",$2}}')
    echo $exec_result  | python -m json.tool

    if [ -z "${tsmap_tso}" ]
    then
        f_PrintLog "Warn" "Binlog tsmap get failed!!!"
        exit 1
    else
        f_PrintLog "Info" "Binlog tsmap is ${tsmap_tso}!"
    fi

}


function f_committs_diff
{
    _ip_s=$1

    f_PrintLog "Info" "Start to run f_committs_diff."
    #最多检查3次,每次间隔10s
    for i in 1 2 3 
    do
        #commit tso
        ck_sql="select checkPoint from ${checkpointschema}.checkpoint order by clusterID desc limit 1"
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip_s}:${tidbPort}"
        exec_result=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
        cmt_tso=$(echo $exec_result  | python -m json.tool | awk '{
        if($1~"commitTS"){gsub(",","",$2);printf "%s\n",$2;exit}
        }')
        echo $exec_result  | python -m json.tool

        ck_sql="select from_unixtime(conv(left(bin('${cmt_tso}'),41),2,10)/1000) "
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip_s}:${tidbPort}"
        exec_result=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
        cmt_ts=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
        
        #time-tso diff
        ck_sql="select timestampdiff(SECOND,TIDB_PARSE_TSO(${cmt_tso}),NOW()) "
        f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip_s}:${tidbPort}"
        exec_result=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
        f_PrintLog "Info" "Binlog commitTS is ${cmt_tso}, ${cmt_ts}, is ${exec_result} seconds (should<30) away from now!"
        
        [ ${exec_result} -lt 30 ] && return 0
        sleep 10
    done 
    return 1
}

function f_backfile
{
    _filename=$1
    if [ -f "${_filename}" ]
    then
        f_PrintLog "Warn" "file ${_filename} already exists, rename it now!!"
        ls -l ${_filename}
        sleep 1
        mv "${_filename}" "${_filename}.bak_${RunTs}"
    fi
}


function f_usergrantsbak
{
    f_PrintLog "Info" "Start to run f_usergrantsbak."
    #提供用户名清单\备份文件名,默认备份全部用户权限
    _filename=$1
    _userlist=$(echo "$2"|tr "," " ")
    _ip=$3
    _port=$4
    f_PrintLog "Info" "start to backup user grants, userlist:${_userlist}, bakfile:${_filename}"
    
    #backup file
    if [ ! -f ${_filename} ]
    then 
        echo "--start backup user grants. $(date +%Y%m%d.%H%M%S)">${_filename}
    elif [ -w ${_filename} ]
    then
        f_PrintLog "Warn" "backup file ${_filename} exist, clean content and overwrite it now."
        ls -l ${_filename}
        sleep 1
        echo "--start backup user grants. $(date +%Y%m%d.%H%M%S)">${_filename}
    else
        ls -l ${_filename}
        f_PrintLog "Error" "file ${_filename} can not write, quit!!!"
        exit 1
    fi
    
    #backup grants info
    for _user in ${_userlist}
    do
        if [ -z "$(echo ${_user}|grep "@")" ] 
        then 
            _user="${_user}@'%'"
        else
            _user="${_user%%@*}@'${_user##*@}'"
        fi

        echo "--${_user}" | tee -a "${_filename}"
        _execsql="SHOW GRANTS FOR ${_user}"
        f_PrintLog "Info" "START TO RUN SQL:${_execsql}, DBinfo ${_ip}:${_port}"
        # echo "mysql -h${tidbip} -P${tidbport} -u${tidbuser} -p123 -NBe ${_execsql} "
        mysql -h${_ip} -P${_port} -u${user} -p${tidbPasswd:-123}  -NBe "${_execsql}" |tee -a "${_filename}"
    done

    #add ;
    sed -i 's/^GRANT.*/&;/g' ${_filename}
    f_PrintLog "Info" "backup user grants finish, backup file is ${_filename}"
    ls -l ${_filename}
}

function f_generatesqlfile
{
f_PrintLog "Info" "Start to run f_generatesqlfile."
f_PrintLog "Info" "parameters: $1 $2 $3 $4"

python -c "
import re,sys

args = sys.argv
infile = args[1]
outfile = args[2]
userlist = args[3]
rvktype = args[4]

userlist_lst = userlist.split(',')
revoke_lst = []

for username in userlist_lst:
    if username == '':
        continue
    with open(infile, mode='r') as f:
        for line in f:
            if not re.search(username, line):
                continue
            elif line.startswith('--'):
                revoke_lst.append(line)
                continue
            elif line.startswith('GRANT USAGE ON'):
                continue
            else:
                line_user = re.findall(r'[\']*\w+[\']*@[\'\w\%]*', line)
                if not re.search(username, line_user[0]):
                    continue

                revoke_all = re.sub(r'(GRANT )([\w, .*]+)( TO )([ \']*\w+[\']*@.*)', r'REVOKE \2 FROM \4', line)
                revoke_read = re.sub(r'(GRANT [\w, .*]+ ON )(.* TO [ \']*\w+[\']*@.*)', r'REVOKE  SELECT  FROM \2', line)
                grant_read = re.sub(r'(GRANT [\w, ]+)( ON .* TO .*)', r'GRANT  SELECT  \2', line, re.IGNORECASE)
            
            if rvktype == 'all':
                revoke_lst.append(revoke_all.replace('WITH GRANT OPTION', ''))
            elif rvktype == 'write':
                revoke_lst.append(revoke_all.replace('WITH GRANT OPTION', ''))
                revoke_lst.append(grant_read)
            elif rvktype == 'read':
                revoke_lst.append(revoke_read.replace('WITH GRANT OPTION', ''))

with open(outfile, mode='w') as f:
     f.write(''.join(revoke_lst))
" "${1}" "${2}" "${3}" "${4}"
f_PrintLog "Info" "Start generate revoke sqlfile finish, sqlfile: ${2}"
ls -l ${2}
#cat ${2}
}

function f_runscp
{
    _file_source=$1
    _file_tartget=$2
    _nodid=$3
    f_PrintLog "Info" "Start to scp file:${_file_source} ${_file_tartget} , remote:${_nodid}"
    tiup cluster push ${clsName} ${_file_source} ${_file_tartget} -N${_nodid}
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "scp usergrant file failed, remote host:${_nodid}, file:${_file_source}"
        return 1
    else
        f_PrintLog "Info" "scp usergrant file finish, remote host:${_nodid}, file:${_file_source}"
    fi

}

function f_scpgrantsql
{
    f_PrintLog "Info" "Start to run f_scpgrantsql."
    tiup cluster exec ${clsName} -N${tidbIp_s} --command "mkdir -p ./switchover/grantsql" 
    # tiup cluster push ${clsName} ${app_bakfile} "./grantsql/usergrant_app_${tidbIp}_$(date +%Y%m%d).sql" -N${tidbIp_s}
    f_runscp ${app_bakfile} "./switchover/grantsql/usergrant_app_${tidbIp}_$(date +%Y%m%d).sql" "${tidbIp_s}"
    f_runscp ${app_rvkfile} "./switchover/grantsql/userrevoke_app_${tidbIp}_$(date +%Y%m%d).sql" "${tidbIp_s}"
    f_runscp ${repl_bakfile} "./switchover/grantsql/usergrant_repl_${tidbIp_s}_$(date +%Y%m%d).sql" "${tidbIp_s}"
    f_runscp ${repl_rvkfile} "./switchover/grantsql/userrevoke_repl_${tidbIp_s}_$(date +%Y%m%d).sql" "${tidbIp_s}"

}

function f_drainerinitts
{
    f_PrintLog "Info" "Start to run f_drainerinitts."
    # initial-commit-ts
    #tiup meta
    #drainer config


}

###############################################################################
##Init##
export LANG=en_US
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};
RunTs=$(date "+%Y%m%d.%H%M%S")
LogFile="${LogDir}/${ShellName}.${RunTs}.log";
Shellcksum=$(cksum ${WorkDir%/}/${ShellName} 2>/dev/null|awk '{printf "%d",$1}')
declare -i UserID=$(id -u);declare UserName=$(whoami);declare HostName=$(hostname);
###############################################################################
##TiDB Var##
port="4000";user="timon";passwd=""
adminusers="root,tidb,timon,repl"
checkpointschema="tidb_binlog"
isswitchback="NO"
p_port=${port};s_port="4100"
###############################################################################
###############################################################################
##Get inopt
[ -z "${ShellOption}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -PRIMARYHOSTNAME|-HOSTNAME) CurOpt="-HOSTNAME_P";continue;;
    -STANDBYHOSTNAME) CurOpt="-HOSTNAME_S";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME_P) declare HostName_P="${inopt}";continue;;
    -HOSTNAME_S) declare HostName_S="${inopt}";continue;;
    esac
done

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

if [ "${HostName_P}" != "${HostName}" -a "${HostName_S}" != "${HostName}" ] 
then
    f_PrintLog "Error" "InputHost are ${HostName_P} and ${HostName_S}, but now i am ${HostName}, exit"
    # exit 1
fi

if [ "${HostName_P}" == "${HostName}" ] 
then
    HostRole="PRIMARY"
elif [ "${HostName_S}" == "${HostName}" ]
then
    HostRole="STANDBY"
else
    HostRole="UNKNOWN"
fi

function f_getclusterinfo
{
    f_PrintLog "Info" "Start to run f_getclusterinfo."
    # clsname,connip,connport,dbsize,dbs,userlist,drainernode,backupdir,repluser
    clsName=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
    if [ -z "${clsName}" ]
    then
        f_PrintLog "Error" "Can not find valid cluster name using:tiup cluster list"
        exit 1
    fi
    f_PrintLog "Info" "find valid cluster name is ${clsName}"
    tiup cluster display ${clsName} 

    tidbclsinfo=$(tiup cluster display ${clsName} 2>/dev/null)
    IPList=$(ip a |awk '/^[1-9]/{gsub(":","",$2);en=$2}
     /^[ |\t]*inet /{gsub(".*:","",$2);gsub("/.*","",$2);if(en!~"^lo")N[$2]=en}
     END{for(ip in N){printf "%s\n",ip}}')
    tidbProc=$(ps -ef | grep "tidb-server -P 4000"| grep -v grep)
    tidbPort=$(echo ${tidbProc}|awk -F"-P" '{print $2}'|awk '{printf "%d",$1}')
    tidbIp=$(echo ${tidbProc}|awk -F"--advertise-address=" '{print $2}'|awk '{printf "%s",$1}')

    tidbNodeId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp}:${tidbPort}" '{
     if($1==id && $2=="tidb" && $6=="Up" ){printf "%s",$1;exit}
     }')

    [ -z "${tidbNodeId}" ] && f_PrintLog "Error" "Can not find valid tidb node ${tidbIp}:${tidbPort}, the cluster name is ${clsName}"

    tidbDrainerId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp%.*}" '{
     if($1!~id && $2=="drainer"){printf "%s",$1;exit}
     }')

    if [ -z "${tidbDrainerId}" ] 
    then
        f_PrintLog "Error" "Can not find valid drainer node, the cluster name is ${clsName}"
    else
        tidbIp_s=${tidbDrainerId%:*}
    fi

    f_PrintLog "Info" "Get ${HostRole} cluster info finished. clsname:${clsName}, Ip:${tidbIp}, Port:${tidbPort}, drainerId:${tidbDrainerId}, standbyIp:${tidbIp_s}"
}

function f_gettidbinfo
{
    f_PrintLog "Info" "Start to run f_gettidbinfo."
    tidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
    adminusers_sql=$(echo "${adminusers}"|sed "s/,/','/g")
    _execsql="select group_concat(concat(user,'@',host) SEPARATOR ',') from  mysql.user where user not in ('${adminusers_sql}')"
    tidbPasswd=$(echo "${passwd}="|base64 -d)
    f_PrintLog "Info" "START TO RUN SQL:${_execsql}, DBinfo ${tidbIp}:${tidbPort}"
    appUsers=$(mysql -h${tidbIp} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${_execsql}")
    if [ -z "${appUsers}" ]
    then
        f_PrintLog "Error" "get app users failed!!!"
        exit 1
    fi

    f_PrintLog "Info" "Get tidb ${tidbIp_s}:${tidbPort} info finished. appUser:${appUsers}, replUser:repl, tidbHome:${tidbHome}"
}

function f_checkreplmain
{
    NumProc=$(awk '/^processor[ |\t]*:/{c++}END{print c}' /proc/cpuinfo 2>/dev/null)
    echo "NumProc:${NumProc}"
    #check binary command
    binary_list="tiup mysql curl dumpling lightning"
    f_checkusedtool "${binary_list}"
    
    #check tidb
    tidbclsinfo=$(tiup cluster display ${clsName}  2>/dev/null)
    f_checktidb ${clsName}

    
    #check binlog status
    tidburl=$(echo "${tidbclsinfo}"|awk '{
        if(NF>=8 && $2=="tidb" && $6=="Up" ){gsub(".*/","",$4);printf "%s:%s\n",$3,$4;exit}
        }')
    if [ -z "${tidburl}" ] 
    then
        f_PrintLog "Error" "Failed to check tidb binlog status. tidburl is null!!!"
        exit 1
    else
        f_PrintLog "Info" "Start to check tidb binlog status. tidburl: http://${tidburl}/info/all "
        f_checktidbbinlog ${tidburl}
    fi

    
    #check connection
    tmp_file="./logs/tmp_apps.txt"
    echo "" > ${tmp_file}
    f_checkconnection "${tidbIp}"
    app_counts=$(wc ${tmp_file}|awk '{printf "%d",$1+$2}')
    if [ ${app_counts} -gt 1 ]
    then
        f_PrintLog "Error" "some applications still use database, check failed, pls stop applications and kill all connections!!!"
        exit 1
    else
        f_PrintLog "Info" "all connections are closed, check pass!"
    fi


    #check replicate 
    f_check_insert "${tidbIp}" "${tidbIp_s}"

    
    #
    f_tsmap_stable "${tidbIp_s}"
    tsmap_a=${tsmap_tso}

    f_committs_diff "${tidbIp_s}"
    rt_code=$?

    #
    f_PrintLog "Info" "Start sleep 120, and confirm tsmap do not change !"
    sleep 120
    f_tsmap_stable "${tidbIp_s}"
    tsmap_b=${tsmap_tso}


    if [ ${rt_code} -eq 0 -a "${tsmap_a}" = "${tsmap_b}" ]
    then 
        f_PrintLog "Info" "Binlog checkpoint's commitTS and tsmap, ${tsmap_a}=${tsmap_b}, check pass!"
    elif [ "${tsmap_a}" != "${tsmap_b}" ]
    then
        f_PrintLog "Warn" "Binlog tsmap changed in 2 minutes, ${tsmap_a}!=${tsmap_b}, drainer still working, check failed!!!"
        exit 1
    elif [ ${rt_code} -ne 0 ]
    then
        f_PrintLog "Warn" "Binlog commitTS not close to now, drainer status may abnormal or stopped already, check failed!!!"
        exit 1
    else
        f_PrintLog "Warn" "Binlog checkpoint's commitTS and tsmap check failed!"
        exit 1
    fi
}


function f_bakusermain
{
    f_PrintLog "Info" "Start to run f_bakusermain."
    #grant sql files
    grantsqldir="${tidbHome}/switchover/grantsql"
    mkdir -p ${grantsqldir}
    app_bakfile=${grantsqldir}"/usergrant_app_${tidbIp}_$(date +%Y%m%d).sql"
    app_rvkfile=${grantsqldir}"/userrevoke_app_${tidbIp}_$(date +%Y%m%d).sql"
    repl_bakfile=${grantsqldir}"/usergrant_repl_${tidbIp_s}_$(date +%Y%m%d).sql"
    repl_rvkfile=${grantsqldir}"/userrevoke_repl_${tidbIp_s}_$(date +%Y%m%d).sql"
    replUser="repl"
    rvkpriv="write"

    #backup primary app user privileges
    _appUsers=""
    for _user in $(echo ${appUsers}|tr "," " ")
    do
      _appUsers="${_appUsers},${_user%%@*}"
    done

    f_backfile "${app_bakfile}" 
    f_usergrantsbak "${app_bakfile}" "${_appUsers}" "${tidbIp}" "${tidbPort}"
    bakok=$(grep "^GRANT" ${app_bakfile} | wc -l)
    if [ ${bakok:-0} -eq 0 ]
    then
        f_PrintLog "Error" "user:${_appUsers} backup failed, pls check ${app_bakfile} !!!"
        exit 1
    fi
    
    #generate revoke write sql
    f_backfile "${app_rvkfile}" 
    f_generatesqlfile "${app_bakfile}" "${app_rvkfile}" "${_appUsers}" "${rvkpriv}"


    #backup standby repl user privileges
    f_backfile "${repl_bakfile}" 
    f_usergrantsbak "${repl_bakfile}" "${replUser}" "${tidbIp_s}" "${tidbPort}"
    bakok=$(grep "^GRANT" ${repl_bakfile} | wc -l)
    if [ ${bakok:-0} -eq 0 ]
    then
        f_PrintLog "Error" "user:${replUser} backup failed, pls check ${repl_bakfile} !!!"
        exit 1
    fi

    f_backfile "${repl_rvkfile}" 
    f_generatesqlfile "${repl_bakfile}" "${repl_rvkfile}" "${replUser}" "${rvkpriv}"

    #scp app sql file to standby
    f_scpgrantsql
}

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

function precheck_main
{
    #获取脚本执行需要的集群信息
    f_getclusterinfo  

    #获取脚本执行需要的数据库连接信息
    f_gettidbinfo 
    f_PrintLog "Info" "Get ${HostRole} cluster info finished. clsname:${clsName}, clsname_s:${clsName_s}, Ip:${tidbIp}, standbyIp:${tidbIp_s}, drainerId:${tidbDrainerId}"

    #执行切换前检查
    f_checkreplmain

    #备份用户权限
    f_bakusermain
}

precheck_main | tee -a ${LogFile}
exit ${PIPESTATUS[0]} 


