#!/bin/env bash
##Description: primary stop repl

script_base_name="2_tidb_fb_standby_dumpling"


function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "bash ${ShellName}  [-primaryhostname <hostname>]"
    echo "-standbyhostname <hostname_standby> -backupdb <db_list>"
    echo " "
    echo " #Description:"
    echo " -primaryhostname ,the primary cluster manager host"
    echo " -standbyhostname ,the standby cluster manager host"
    echo " -backupdb ,the databases need to backup, eg: db1,db2,test"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -primaryhostname 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}";
    declare LogFile="${LogFile:-"/tmp/${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
}

###############################################################################

function f_backfile
{
    _filename=$1
    _filepath="${_filename%/*}/baktmp"
    [ ! -d ${_filepath} ] && mkdir -p "${_filepath}"
    if [ -f "${_filename}" ]
    then
        f_PrintLog "Warn" "file ${_filename} already exists, rename it now!!"
        ls -l ${_filename}
        sleep 1
        mv "${_filename}" "${_filepath}/${_filename##*/}.bak_$(date +%Y%m%d.%H%M%S)"
    fi
}

function f_committs_stop
{
    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 ${connOk}"
        exec_result=$(mysql --login-path=${locallogin:-tidblogin} -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 --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        
        #time-tso diff
        ck_sql="SELECT timestampdiff(SECOND,TIDB_PARSE_TSO(${cmt_tso}),NOW()) "
        exec_result=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${ck_sql}")
        f_PrintLog "Info" "Drainer checkpoint consistent is ${consistent} (should be true), commitTS is ${cmt_tso}, ${cmt_ts}, is ${exec_result} (>30 & <3600) seconds away from now!"
        
        [ ${exec_result} -gt 30 -a ${exec_result} -le 3600 -a "${consistent}" = "true" ] && return 0
        sleep 10
    done 
    f_PrintLog "Error" "Drainer checkpoint check failed, drainer not not stop normally, pls check!!!"
    exit 1
}


function f_revoke_repl
{
    f_PrintLog "Info" "Start to run f_revoke_repl."
    f_PrintLog "Info" "repl grants before revoke..."
    f_PrintLog "Info" "mysql --login-path=${locallogin:-tidblogin} -e show grants for repl@'%'"
    mysql --login-path=${locallogin:-tidblogin} -e "show grants for repl@'%'"
    f_PrintLog "Info" "mysql --login-path=${locallogin:-tidblogin} -e revoke Insert,Update,Delete,Create,Drop,Alter,Execute,Index on *.* from repl@'%'"
    mysql --login-path=${locallogin:-tidblogin} -e "revoke Insert,Update,Delete,Create,Drop,Alter,Execute,Index on *.* from repl@'%'"
    local _rt_code=$?
    f_PrintLog "Info" "repl grants after revoke..."
    f_PrintLog "Info" "mysql --login-path=${locallogin:-tidblogin} -e show grants for repl@'%'"
    mysql --login-path=${locallogin:-tidblogin} -e "show grants for repl@'%'"

    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "revoke write grants from repl successfully."
    else
        f_PrintLog "Error" "revoke write grants from repl failed, return:${_rt_code}."
        exit 1
    fi 
}

function f_runsqlfile
{
    _sqlfile=$1

    connstr="--login-path=${locallogin:-tidblogin}"


    f_PrintLog "Info" "START TO RUN SQL:${_sqlfile}, DBinfo ${connstr}"
    echo -e "/n*************************************************************"
    cat ${_sqlfile}
    echo -e "\n*************************************************************"
    f_PrintLog "Info" "PLS CHECK ALL COMMANDS IN FILE, SLEEP 3......"
    sleep 3
    echo "mysql ${connstr} -vvv < ${_sqlfile}"
    mysql ${connstr} -vvv < ${_sqlfile}
    return $?
}

function f_appuser_grant
{
    f_PrintLog "Info" "Start to run f_appuser_grant."
    f_PrintLog "Info" "get appuser grants..."
    f_PrintLog "Info" "mysql --login-path=${locallogin:-tidblogin} -e select concat(user,'@','''',host,'''') from mysql.user where user not in ('root','tidb','timon','dsg','repl')"
    mysql --login-path=${locallogin:-tidblogin} -e "select concat(user,'@','''',host,'''') from mysql.user where user not in ('root','tidb','timon','dsg','repl')"
    _appuser_list=$(mysql --login-path=${locallogin:-tidblogin} -NBe "select concat(user,'@','''',host,'''') from mysql.user where user not in ('root','tidb','timon','dsg','repl')")
    echo "" > ${WorkDir}/appuser.grant.sql
    for _user in ${_appuser_list}
    do
        f_PrintLog "Info" "mysql --login-path=${locallogin:-tidblogin} -e show grants for ${_user}"
        mysql --login-path=${locallogin:-tidblogin} -NBe "show grants for ${_user}" | tee -a ${WorkDir}/appuser.grant.sql
    done
    
python -c "
import re,sys

args = sys.argv
grant_file = args[1]
grant_rw_file = args[2]
grant_r_file = args[3]

grant_lst = []
revoke_lst = []

with open(grant_file, mode='r') as fd:
    for line in fd:
        line = line.strip()
        if line == '':
            continue
        if not line.endswith(';'):
            line = line + ';'
        grant_rw_stmt = re.sub(r'(GRANT )([\w, .*]+)( ON [\w .*]+ TO [ \']*\w+[\']*@.*)', r'GRANT Select,Insert,Update,Delete,Create,Drop,Alter,Execute,Index \3', line)
        grant_r_stmt = re.sub(r'(GRANT )([\w, .*]+)( ON [\w .*]+ TO [ \']*\w+[\']*@.*)', r'GRANT Select \3', line)
        revoke_rw_stmt = re.sub(r'(GRANT [\w, .*]+ ON)([\w .*]+)( TO )([ \']*\w+[\']*@.*)', r'REVOKE Select,Insert,Update,Delete,Create,Drop,Alter,Execute,Index ON \2 FROM \4', line)
        grant_lst.append(grant_rw_stmt)
        revoke_lst.append(revoke_rw_stmt)
        revoke_lst.append(grant_r_stmt)

with open(grant_rw_file, mode='w') as fd:
    fd.write('\n'.join(grant_lst))

with open(grant_r_file, mode='w') as fd:
    fd.write('\n'.join(revoke_lst))
" "${WorkDir}/appuser.grant.sql" "${WorkDir}/appuser.grant_readwrite.sql" "${WorkDir}/appuser.grant_read.sql"
    
    f_PrintLog "Info" "get appuser grants finish."
    ls -l ${WorkDir}/appuser*.sql

    f_runsqlfile "${WorkDir}/appuser.grant_readwrite.sql" 
    _rt_code=$?
    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info" "grant app user write privileges finish!"
    else
        f_PrintLog "Error" "grant app user write privileges failed!!!"
        exit 1
    fi
}


function f_CheckDumplingCount
{
    f_PrintLog "Info" "Start to run f_CheckDumplingCount."
    MaxRunningCount=0
    ##Check ShellCount##
    for i in 1 2 3 4 5
    do
        ShellCount=$(ps -ef|grep "dumpling"|grep -vE "$$|cat|more|vi|view|grep|tail|tee"|awk 'END{print NR}')
        if [ ${ShellCount} -le ${MaxRunningCount:-0} ]
        then
            break
        fi

        ps -ef|grep "dumpling"|grep -vE "$$|cat|more|vi|view|grep|tail|tee"
        f_PrintLog "Warn" "dumpling is running, running count:${ShellCount}, greater then ${MaxRunningCount:-0}, continue ${i}";
        sleep 10
    done

    if [ ${ShellCount} -gt ${MaxRunningCount:-0} ]
    then
        ps -ef|grep "dumpling"
        f_PrintLog "Error" "Dumpling is current running, current pid is $$, exit!!!";
        exit 1
    fi
}

function f_backupsizecheck
{
    _clsname=$1

    f_PrintLog "Info" "Start to run f_backupsizecheck."
    
    pdNode=$(tiup cluster display ${_clsname}  2>/dev/null |awk  '{
        if($2=="pd" && $6~"Up"){printf "%s\n",$1;exit}
        }')
    f_PrintLog "Info" "Get cluster size pd-ctl ${pdNode}"
    pdRepls=$(pd-ctl --pd="http://${pdNode}" config show replication | awk -F: '{if($1~"max-replicas"){gsub(",","",$2);printf "%d",$2;exit}}')
    storeSize=$(pd-ctl --pd="http://${pdNode}" store | awk '{if($1~"used_size"){gsub(",","",$2);gsub("\"","",$2);printf "%s\t",$2}}')
    sizeMB=0
    for _size in ${storeSize}
    do
        _sizemb=$(echo ${_size}|awk '
            /.*KiB/{gsub("KiB","",$1);sz=$1/1000}
            /.*MiB/{gsub("MiB","",$1);sz=$1}
            /.*GiB/{gsub("GiB","",$1);sz=$1*1000}
            /.*TiB/{gsub("TiB","",$1);sz=$1*1000000}
            END{printf "%d\n",sz}
            ')
        sizeMB=$((sizeMB+_sizemb))
    done
    f_PrintLog "Info" "Cluster ${_clsName} size is ${sizeMB}MiB, max-replicas:${pdRepls}"
    sizeMB=$((sizeMB/pdRepls*3/2))
    
    df -h
    diskFree=$(df -P -m ${backupdir}|awk '!/Filesystem/{printf "%d",$4;exit}')
    if [ ${diskFree:-1} -gt ${sizeMB:-1} ]
    then
        f_PrintLog "Info" "backup dir ${backupdir} free space is ${diskFree}MB, greater then dbsize ${sizeMB}MB"
    else
        f_PrintLog "Error" "backup dir ${backupdir} free space is ${diskFree}MB, less then dbsize ${sizeMB}MB, quit!!!"
        exit 1
    fi
}


function f_dumplingpid
{
    f_PrintLog "Info" "Start to run f_dumplingpid."
    if [ ! -f "${dumppidfile}" ] 
    then
        touch ${dumppidfile}
    else
        f_PrintLog "Info" "List current pid file:${dumppidfile}"
        #list old file
        echo "************************"
        ls -l  ${dumppidfile}
        cat ${dumppidfile}
        echo "************************"
        f_backfile "${dumppidfile}" 
    fi

    f_PrintLog "Info" "Generate new pid file.${dumppidfile}"
    #pid file for lightning
    echo "RUNTS=${RunTs}"                  >  "${dumppidfile}"
    echo "TIDBIP=${tidbIp}"                >> "${dumppidfile}"
    echo "DBSIZE=${sizeMB}"                >> "${dumppidfile}"
    echo "BAKDIR=${_backupdir}"            >> "${dumppidfile}"
    echo "LOGFILE=${_baklogfile}"          >> "${dumppidfile}"
    echo "SNAPSHOTTM=\"${_snapshot}\""         >> "${dumppidfile}"
    echo "SNAPSHOTTSO=${_snaptso}"         >> "${dumppidfile}"
    echo "CHECKPOINTCOMMITTM=\"${cmt_ts}\""    >> "${dumppidfile}"
    echo "CHECKPOINTCOMMITTSO=${cmt_tso}"  >> "${dumppidfile}"

    f_PrintLog "Info" "List new pid file.${dumppidfile}"
    #list new file
    echo "************************"
    ls -l  ${dumppidfile}
    cat ${dumppidfile}
    echo "************************"

}


function f_rundumpling
{
    _ip=$1

    f_PrintLog "Info" "Start to run f_rundumpling. $1"
    
    #dumpling config
    numProc=$(awk '/^processor[ |\t]*:/{c++}END{print c}' /proc/cpuinfo 2>/dev/null)
    if [ ${numProc} -ge 40 ]
    then
        thread=24
    elif [ ${numProc} -ge 20 ]
    then
        thread=12
    else
        thread=4
    fi

    enginetype='tidb_isolation_read_engines=tikv'
    _snapshot=$(date "+%Y-%m-%d %H:%M:%S")
    _backupdir=${backupdir}/dumpling/${RunTs}
    _baklogfile=${backupdir}/dumpling/logs/dumpling_${_ip}_${RunTs}.log
    _snaptso=$(mysql --login-path=tidblogin -NBe "select conv(concat(bin(unix_timestamp(now())*1000),'000000000000000001'),2,10)")

    if [ ! -d ${backupdir} ]
    then
        f_PrintLog "Error" "backup dir ${backupdir} not exists, exit!!!"
        exit 1
    fi

    mkdir -p ${backupdir}/dumpling/${RunTs}
    mkdir -p ${backupdir}/dumpling/logs

    [ -n "${backupdb}" ] && db_option="-B ${backupdb}" || db_option=""
    [ -n "${_snaptso}" ] && snap_option="--snapshot ${_snaptso}"
    conn_option="-h${_ip} -P${tidbPort} -u${user}"
    dir_option="-o ${_backupdir}"
    par_option="--filetype sql --params ${enginetype} -t ${thread} -r 200000 -F 256MiB"

    dumpling -V
    f_PrintLog "Info" "start to run dumpling backup, log file:${_logfile} "
    f_PrintLog "Info" "parameter: ${conn_option} ${dir_option} ${db_option} ${par_option} -p "

    echo "dumpling ${conn_option} ${dir_option} ${db_option} ${snap_option} ${par_option} -p xxx 2>&1 >> ${_baklogfile} "
    sleep 3
    dumpling ${conn_option} ${dir_option} ${db_option} ${snap_option} ${par_option} -p${tidbPasswd:-123}  2>&1  >> ${_baklogfile}  &
    f_PrintLog "Info" "run tiup dumpling finished background, backup dir is ${_backupdir} "
    ps -ef|grep "dumpling"
    sleep 10
    
    dumplingCount=$(ps -ef|grep "dumpling"|grep -vE "grep|tail|tee" |wc -l)
    dumplingSucc=$(tail ${_baklogfile}|grep "dump data successfully"|wc -l)

    ck_sql="select user,count(1) from information_schema.cluster_processlist group by user"
    f_PrintLog "Info" "START TO RUN SQL:${ck_sql}, DBinfo ${_ip}"
    mysql ${conn_option} -p${tidbPasswd:-123} -vvv -e "${ck_sql}"

    if [ ${dumplingCount:-0} -ge 1 ]
    then
        f_PrintLog "Info" "Dumpling is running background, pls monitor it and check the log file ${_baklogfile}"
    elif [ ${dumplingSucc} -eq 1 ]
    then
        f_PrintLog "Info" "Dumpling already finished, pls check the log file ${_baklogfile}"
    else
        f_PrintLog "Error" "Dumpling was not start running, pls check the log file ${_baklogfile}"
        exit 1
    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 4"| 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 "Warn" "Can not find valid tidb node ${tidbIp}:${tidbPort}, the cluster name is ${clsName}"

    #根据drainerid是否等于tidbid判断drainer归属
    tidb_urls=$(tiup cluster display ${clsName} 2>/dev/null|awk '{if($2=="tidb"){gsub(":.*","",$1);printf "%s ",$1}}')
    dr_urls=$(tiup cluster display ${clsName} 2>/dev/null|awk '{if($2=="drainer"){printf "%s,%s ",$1,$6}}')
    for drid in ${dr_urls}
    do
        _localflag=$(echo ${tidb_urls} |grep -w ${drid%:*})
        _Upflag=$(echo ${drid} |grep -w "Up")
        if [ -z "${_localflag}" ]
        then
            drainerRemote="${drainerRemote}${drid}"
            [ -n "${_Upflag}" ] && drainerRemoteUp="${drainerRemoteUp}${drid}"
            f_PrintLog "Info" "Find a remote drainer ${drid}, drainerRemote:${drainerRemote}"
        else
            drainerLocal="${drainerLocal}${drid}"
            [ -n "${_Upflag}" ] && drainerLocalUp="${drainerLocalUp}${drid}"
            f_PrintLog "Info" "Find a locale drainer ${drid}, drainerLocal:${drainerLocal}"
        fi
    done
    
    _drCt=$(echo ${drainerRemote}|awk -F: '{print NF}')
    if [ ${_drCt} -gt 2 ]
    then
        f_PrintLog "Error" "The remote drainer count is ${_drCt}, exit!!!"
        exit 1
    fi

    t2fDrId=${drainerLocal}
    t2tDrId=${drainerRemote}
    tidbDrainerId=${drainerRemote}
    drainerRemote=${drainerRemoteUp}

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

    adminusers_sql=$(echo "${adminusers}"|sed "s/,/','/g")
    _execsql="select group_concat(concat(user,'@',host) SEPARATOR ',') from  mysql.user where user not in ('${adminusers_sql}')"
    f_PrintLog "Info" "START TO RUN SQL:${_execsql}, DBinfo ${tidbIp}:${tidbPort}"
    appUsers=$(mysql --login-path=${locallogin:-tidblogin} -NBe "${_execsql}")

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


###############################################################################
##Init##
export LANG=en_US
TidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
NumProc=$(awk '/^processor[ |\t]*:/{c++}END{print c}' /proc/cpuinfo 2>/dev/null)
ShellName="$(echo $0|awk -F / '{print $NF}')";ShellOption="$@";
WorkDir="$(echo $0|sed s/${ShellName}//g)";[ -z "${WorkDir}" ] && WorkDir=${PWD};cd ${WorkDir};WorkDir=${PWD}
LogDir="${TidbHome}/scripts/flashback/logs";mkdir -p ${LogDir};
RunTs=$(date "+%Y%m%d.%H%M%S")
LogFile="${LogDir}/${script_base_name}_${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##
locallogin=""
adminusers=""
checkpointschema=""
nobackupdatabase="INFORMATION_SCHEMA,METRICS_SCHEMA,PERFORMANCE_SCHEMA,mysql,tidb_binlog"
backupdir=""
user=""
tidbPasswd=""
tidbsoconfig="${TidbHome}/scripts/flashback/cluster_flashback.config"
dumppidfile="${backupdir}/dumpling/cluster_flashback_dumpling.pid"
[ -f ${tidbsoconfig} ] && source ${tidbsoconfig}
###############################################################################
###############################################################################
##Get inopt
# [ -z "${ShellOption}" -a -z "${primaryhostname}" -a -z "${standbyhostname}" ] && 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;;
    -BACKUPDB) CurOpt="-BACKUPDB";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME_P) declare primaryhostname="${inopt}";continue;;
    -HOSTNAME_S) declare standbyhostname="${inopt}";continue;;
    -BACKUPDB) declare backupdb="${inopt}";continue;;
    esac
done


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

function f_checkdrainerstop
{
    f_PrintLog "Info" "Start to run f_checkdrainerstop."
    mysql --login-path=${locallogin:-tidblogin} -NBe "select * from tidb_binlog.checkpoint"
    f_committs_stop 
}


function f_dumplingmain
{
    f_PrintLog "Info" "Start to run f_dumplingmain."
    if [ -z "${backupdir}" -o ! -d "${backupdir}" ]
    then
        f_PrintLog "Error" "backupdir ${backupdir} not exists, exit!!!"
        exit 1
    fi

    f_CheckDumplingCount
    f_backupsizecheck "${clsName}"
    f_rundumpling "${tidbIp}"
    f_dumplingpid

}


###################
####    Main   ####
###################
function f_fb_standby_dumpling_main
{
    #判断集群为备集群
    #判断drainer状态为复制停止状态
    #执行全库备份
    #应用用户增加写入权限
    f_PrintLog "Info" "Start to run Script ${ShellName} on ${HostName}, script_base_name ${script_base_name}."

    #local var
    localProc=$(ps -ef | grep "tidb-server -P 4"| grep -v grep)
    localPort=$(echo ${localProc}|awk -F"-P" '{print $2}'|awk '{printf "%d",$1}')
    localIp=$(echo ${localProc}|awk -F"--advertise-address=" '{print $2}'|awk '{printf "%s",$1}')
    tidbIpLocal="${localIp}"

    #check script var
    clsName=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
    tidbPort="${localPort}"
    tidbIp="${localIp}"

    # 获取集群信息
    # f_getclusterinfo
    
    # 不能使用loginpath=tidblogin登录的机器,不符合部署规范,不执行
    connOk=$(mysql --login-path=${locallogin:-tidblogin} -NBe "select user()")
    if [ -z "${connOk}" ]
    then
        f_PrintLog "Error" "No passwd login failed, pls check mysql --login-path=${locallogin:-tidblogin} "
        exit 1
    else
        f_PrintLog "Info" "No passwd login successfully, connect user is ${connOk}, check pass!"
    fi

    # 检查drianer状态
    f_checkdrainerstop

    # 回收repl用户权限
    f_revoke_repl

    # 执行备份
    f_dumplingmain

    # 备份配置文件准备

    # 应用用户赋权
    f_appuser_grant
    
    f_PrintLog "Succ" "Run function f_fb_standby_dumpling_main finish!"
    f_PrintLog "Info" "Successful to run Script ${ShellName} on ${HostName}, script_base_name ${script_base_name}."
    exit 0
}


 
f_fb_standby_dumpling_main

