#!/bin/env bash
##Description: start replicate  

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 2
}

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_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_stop
{
    _ip_s=$1

    f_PrintLog "Info" "Start to run f_committs_stop."
    #最多检查3次,每次间隔10s
    for i in 1 2 3 
    do

        #commit ts0
        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}")
        if [ $? -ne 0 ]
        then
            f_PrintLog "Error" "run check sql failed, STMT:${ck_sql}, pls check!!!"
            exit 1
        fi

        cmt_tso=$(echo $exec_result  | python -m json.tool | awk '{
        if($1~"commitTS"){gsub(",","",$2);printf "%s\n",$2;exit}
        }')
        consistent=$(echo $exec_result  | python -m json.tool | awk '{
        if($1~"consistent"){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) "
        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()) "
        exec_result=$(mysql -h${_ip_s} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
        f_PrintLog "Info" "Drainer checkpoint consistent is ${consistent} (should be true), commitTS is ${cmt_tso}, ${cmt_ts}, is ${exec_result} (should>30) seconds away from now!"
        
        [ ${exec_result} -gt 60 -o "${consistent}" = "true" ] && return 0
        sleep 10
    done 
    f_PrintLog "Error" "Drainer checkpoint check failed, drainer maybe in running, pls check!!!"
    exit 1
}


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_drop_checkpoint
{
    _ip=$1
    f_PrintLog "Info" "Start to run f_drop_checkpoint."
    #sql
    drop_tab="drop table ${checkpointschema}.checkpoint"
    select_tab="select * from ${checkpointschema}.checkpoint"
    
    #Primary
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${select_tab}"
    f_runsqlstmt "${_ip}" "${tidbPort}" "${user}" "${tidbPasswd:-123}"  "${drop_tab}"
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "exec sql failed, stmt:${drop_tab}"
        exit 1
    fi
}

function f_sacleoutdrainer
{
    _clsname=$1
    _scaleyaml=$2
    f_PrintLog "Info" "Start to scale cluster ${_clsname}, config file:${_scaleyaml}"
    cat ${_scaleyaml}
    sleep 3
    _nd_true=$(awk -F: '{if($1~"ignore_exporter"){gsub(" ","",$2);printf "%s",$2}}' ${_scaleyaml} 2>/dev/null )
    if [ "${_nd_true}" != "true" ]
    then
        f_PrintLog "Warn" "config file not contain ignore_exporter=true, pls check yaml file: ${_scaleyaml}"
        # exit 1
    fi

    tiup cluster scale-out ${_clsname} ${_scaleyaml} --yes --wait-timeout 60 
    _rt_code=$?

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

    if [ ${_rt_code} -eq 0 -a -n "${newDrainerId}" ]
    then
        f_PrintLog "Info" "tiup cluster scale-out finish, drainer id:${newDrainerId}"
    else
        f_PrintLog "Error" "tiup cluster scale-out fail, pls check logs!!!"
        exit 1
    fi    
}

function f_runsqlfile
{
    _sqlfile=$1
    _ip=$2
    _port=$3

    f_PrintLog "Info" "START TO RUN SQL:${_sqlfile}, DBinfo ${_ip}:${_port}"
    echo "*************************************************************"
    cat ${_sqlfile}
    echo "*************************************************************"
    f_PrintLog "Info" "PLS CHECK ALL COMMANDS IN FILE, SLEEP 3......"
    sleep 3
    echo "mysql -h${_ip} -P${_port} -u${user} -p123 -vvv < ${_sqlfile}"
    mysql -h${_ip} -P${_port} -u${user} -p${tidbPasswd:-123} -vvv < ${_sqlfile}
    return $?
}


function f_tiupcmd
{
    f_PrintLog "Info" "Start to run f_tiupcmd."
    cls_name="$1"
    component_name="$2"
    action="$3"
    
    f_PrintLog "Info" "Start to ${action} ${component_name} on cluster ${cls_name} ..."
    sleep 3
    #clsinfo 
    tiup cluster ${action} ${cls_name} -N${component_name} --yes --wait-timeout 60
    rt_code=$?
    if [ ${rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "${action} ${component_name} on cluster ${cls_name} successfully!"
        return ${rt_code}
    else
        f_PrintLog "Error" "${action} ${component_name} on cluster ${cls_name} failed!!!"
        return ${rt_code}
    fi
}


function f_startdrainer
{
    _clsname=$1

    f_PrintLog "Info" "Start to run f_startdrainer."
    #check tidb
    tiup cluster display ${_clsname}
    if [ -z "${tidbNodeId}" ] 
    then
        f_PrintLog "Error" "Can not find valid tidb node ${tidbIp_s}:${tidbPort}, the cluster name is ${clsName_s}"
        exit 1
    fi

    #drainer ip handle
    tidbclsinfo=$(tiup cluster display ${_clsname}  2>/dev/null)
    tidbIDIP=${tidbNodeId%:*}

    #启动停止的drainer
    drainerStatus=$(echo "${tidbclsinfo}"|awk -v id="${tidbIDIP}" '{
        if($1!~id && $2=="drainer"){printf "%s",$6;exit}
        }')

    drainerID=$(echo "${tidbclsinfo}"|awk -v id="${tidbIDIP}" '{
        if($1!~id && $2=="drainer"){printf "%s",$1;exit}
        }')

    if [ "${drainerStatus}" = "Up" ]
    then
        f_PrintLog "Warn" "Drainer ${tidbDrainerId} status is ${drainerStatus}, not need to start." 
        return 0   
    elif [ "${drainerStatus}" = "Down" ]
    then
        action="start"
        f_tiupcmd "${_clsname}" "${drainerID}" "${action}"
        rt_code=$?
    else
        f_PrintLog "Error" "Drainer ${tidbDrainerId} status is ${drainerStatus}, exit!!!"
        exit 1
    fi


    tiup cluster display ${_clsname} 
    tidbclsinfo=$(tiup cluster display ${_clsname} 2>/dev/null)
    drok=$(echo "${tidbclsinfo}"|awk -v dip="${drainerID}" '{
        if($1==dip && $2=="drainer" && $6=="Up"){printf "%s",$1;exit}
        }')

    if [ ${rt_code} -eq 0 -a -n "${drok}" ]
    then
        f_PrintLog "Info" "cluster ${_clsname} node ${drainerID} ${action} finish!"    
    else
        f_PrintLog "Error" "cluster ${_clsname} node ${drainerID} ${action} failed !!!"
        exit 1
    fi

}



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}"

    
    s_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}"
        p_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_grant_user
{
    _ip=$1
    _grantfile=$2 

    f_PrintLog "Info" "Start to run f_grant_user"
    if [ ! -f "${_grantfile}" ]
    then
        f_PrintLog "Error" "User grant backup file not exits, pls check ${_grantfile}, quit!!!"
        # exit 1
    fi

    f_runsqlfile "${_grantfile}" "${_ip}" "${tidbPort}"
    _rt_code=$?
    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "User grant backup file exec finish!"
    else
        f_PrintLog "Error" "User grant backup file exec failed!!!"
        # exit 1
    fi

}


# function f_grant_appuser
# {
#     _ip=$1

#     f_PrintLog "Info" "Start to run f_grant_appuser"
#     grantstmt_file="${tidbHome}/switchover/grantsql/usergrant_app_${tidbIp}_$(date +%Y%m%d).sql"
#     if [ ! -f "${grantstmt_file}" ]
#     then
#         f_PrintLog "Error" "Primary cluster app user backup file not exits, filename should be ${grantstmt_file}, quit!!!"
#         exit 1
#     fi

#     f_runsqlfile "${grantstmt_file}" "${_ip}" "${tidbPort}"
#     _rt_code=$?
#     if [ ${_rt_code} -eq 0 ]
#     then
#         f_PrintLog "Info" "grant app user privileges finish!"
#     else
#         f_PrintLog "Error" "grant app user privileges failed!!!"
#         exit 1
#     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_checkbinlog
{
    _clsname=$1

    #check tidb
    tidbclsinfo=$(tiup cluster display ${_clsname} 2>/dev/null)

    #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
}


###############################################################################
##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

f_PrintLog "Info" "InputHost are ${HostName_P} and ${HostName_S}, now i am ${HostName}, the hostrole:${HostRole}"


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 "Warn" "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 clean_checkpoint
{
    _ip=$1
    ck_sql="select count(1) from information_schema.tables where table_name='checkpoint' and table_schema='${checkpointschema}'"
    f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip}:${tidbPort}"
    exec_result=$(mysql -h${_ip} -P${tidbPort} -u${user} -p${tidbPasswd:-123} -NBe "${ck_sql}")
    if [ $? -eq 0 -a "${exec_result:-1}" = "0" ]
    then
        f_PrintLog "Warn" "checkpoint table not exists, skip drop table ${checkpointschema}.checkpoint!"
        return 0
    fi

    f_committs_stop "${_ip}"
    f_drop_checkpoint "${_ip}"
    f_PrintLog "Info" "Drop table ${checkpointschema}.checkpoint finish."
}



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

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

    #获取脚本执行需要的数据库连接信息
    f_gettidbinfo 

    #转换获取的参数值
    tmp_var=${tidbIp}
    tidbIp=${tidbIp_s}
    tidbIp_s=${tmp_var}
    clsName_s=${clsName}
    f_PrintLog "Info" "Get ${HostRole} cluster info finished. clsname:${clsName}, clsname_s:${clsName_s}, Ip:${tidbIp}, standbyIp:${tidbIp_s}, drainerId:${tidbDrainerId}"

    #删除备库上的checkpoint表
    [ -z "${checkpointschema}" ] && checkpointschema="tidb_binlog"
    clean_checkpoint "${tidbIp_s}"  

    #检查备库的binlog状态
    f_checkbinlog "${clsName}" 

    
    #部署反向drainer
    tidbDrainerId=$(tiup cluster display ${clsName} 2>/dev/null|awk -v id="${tidbIp_s%.*}" '{
        if($1!~id && $2=="drainer"){printf "%s",$1;exit}
        }')
    
    if [ -z "${tidbDrainerId}" ]
    then
        f_PrintLog "Info" "Can not find valid drainer node, the cluster name is ${clsName_s}, start to scale-out."
        if [ -f "${tidbHome}/switchover/${clsName_s}_scaleout_slave_drainer.yaml" ]
        then
            f_PrintLog "Info" "Start to scale-out drainer, the config file is:${tidbHome}/${clsName_s}_scaleout_slave_drainer.yaml"
            f_sacleoutdrainer "${clsName_s}" "${tidbHome}/switchover/${clsName_s}_scaleout_slave_drainer.yaml"
        else
            f_PrintLog "Error" "Tiup scale-out yaml not exist, pls provide ${tidbHome}/switchover/${clsName_s}_scaleout_slave_drainer.yaml"
            exit 1
        fi
    else
        #恢复主库的repl权限
        repl_bakfile="${tidbHome}/switchover/grantsql/usergrant_repl_${tidbIp_s}_$(date +%Y%m%d).sql"
        f_grant_user "${tidbIp}" "${repl_bakfile}"

        #启动反向drainer
        f_startdrainer "${clsName_s}" "${tidbDrainerId}" 
    fi

    f_getclusterinfo
    #转换获取的参数值
    tmp_var=${tidbIp}
    tidbIp=${tidbIp_s}
    tidbIp_s=${tmp_var}
    clsName_s=${clsName}


    #进行写入数据测试
    f_check_insert "${tidbIp_s}" "${tidbIp}"

    #备集群的应用用户授权
    app_bakfile="${tidbHome}/switchover/grantsql/usergrant_app_${tidbIp}_$(date +%Y%m%d).sql"
    app_rvkfile="${tidbHome}/switchover/grantsql/userrevoke_app_${tidbIp}_$(date +%Y%m%d).sql"
    repl_bakfile="${tidbHome}/switchover/grantsql/usergrant_repl_${tidbIp_s}_$(date +%Y%m%d).sql"
    repl_rvkfile="${tidbHome}/switchover/grantsql/userrevoke_repl_${tidbIp_s}_$(date +%Y%m%d).sql"
    f_grant_user "${tidbIp_s}" "${app_bakfile}"
    f_grant_user "${tidbIp}" "${app_rvkfile}"
    f_grant_user "${tidbIp_s}" "${repl_rvkfile}"

}

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

