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

script_run_role="STANDBY"
script_base_name="tidb_fb_standby_lightning"


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 " -restoredb ,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_get_committs
{
    f_PrintLog "Info" "Start to run f_get_committs."


        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} seconds away from now!"
        

}


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

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

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

function f_generateconfig
{
    f_PrintLog "Info" "Start to run f_generateconfig."
    echo "${BAKDIR}" "${tidbPD}" "${tidbPasswd:-123}" "${lightingdir}" "${RunTs}" 

python -c "
import sys,time

args = sys.argv
dumplingdir = args[1]
pdaddr = args[2]
tidbpasswd = args[3]
filedir = args[4]
file_suffix = args[5]
restore_tabs = args[6]

tabs_lst = restore_tabs.split(',')
tabs2_lst = []
for tab in tabs_lst:
    if '.' not in tab:
        tab = tab + '.*'
    tabs2_lst.append('\"%s\"' %(tab) )
restoretabs_str = ','.join(tabs2_lst)

config_text = '''
[lightning]
level = 'info'
file = '%s/tidb-lightning.%s.log'

check-requirements = false

[mydumper]
data-source-dir = '%s'
filter = [%s]

[tikv-importer]
backend = 'local'

sorted-kv-dir = '/data/tidbbackup/lightning_tmp'

[tidb]
host = '127.0.0.1'
port = 4900
user = 'tidb'
password = '%s'
status-port = 10183
pd-addr = '%s'
log-level = 'error'

[post-restore]
checksum = 'required'
analyze = 'off'

[cron]
log-progress = '1m'
''' % (filedir, file_suffix, dumplingdir, restoretabs_str, tidbpasswd, pdaddr)

config_file='%s/lightning_%s.toml' %(filedir, file_suffix)

with open(config_file, mode='w') as f:
     f.write(config_text)
" "${BAKDIR}" "${tidbPD}" "${tidbPasswd:-123}" "${lightingdir}" "${RunTs}" "${restoredb}"
    
    f_PrintLog "Info" "run lightning f_generateconfig finished, pls check ${lightingdir}/lightning_${RunTs}.toml"
    ls -l ${lightingdir}/lightning_${RunTs}.toml
    cat ${lightingdir}/lightning_${RunTs}.toml
}


function f_runlightning
{

    f_PrintLog "Info" "Start to run f_runlightning."
    
    #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

    lightingdir=${backupdir}/lightning/${RunTs}
    lightinglog=${backupdir}/lightning/${RunTs}/logs/lightning_${RunTs}.log

    mkdir -p ${lightingdir}/logs
    

    tidb-lightning -V
    f_PrintLog "Info" "start to run tidb-lightning restore, log file:${lightinglog} "
    f_generateconfig

    f_PrintLog "Info"  "tidb-lightning -config ${lightingdir}/lightning_${RunTs}.toml >> ${lightinglog}  2>&1 "
    ps -ef|grep "tidb-lightning"
    sleep 10

    tidb-lightning -config ${lightingdir}/lightning_${RunTs}.toml >> ${lightinglog}  2>&1
    _rt_code=$?
    f_PrintLog "Info" "run tidb-lightning finish, return code:${_rt_code} "
    
    lightningSucc=$(tail ${lightinglog}|grep "successfully"|wc -l)
    lightningErro=$(cat ${lightinglog}|grep -i "ERROR"|wc -l)

    if [ ${_rt_code} -eq 0 -a ${lightningSucc:-0} -ge 1 -a ${lightningErro:-0} -eq 0 ]
    then
        f_PrintLog "Info" "tidb-lightning running successfully, pls check the log file ${lightinglog}"
    else
        f_PrintLog "Error" "tidb-lightning running successfully failed,return code:${_rt_code}:${lightningSucc}:${lightningErro}, pls check the log file ${lightinglog}"
        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;exit}'|awk '{printf "%d",$1}')
    tidbIp=$(echo ${tidbProc}|awk -F"--advertise-address=" '{print $2;exit}'|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 ${HostRole} 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=""
dumppidfile="${backupdir}/dumpling/cluster_flashback_dumpling.pid"
[ -f ${dumppidfile} ] && source ${dumppidfile}
tidbfbconfig="${TidbHome}/scripts/flashback/cluster_flashback_config.cnf"
[ -f ${tidbfbconfig} ] && source ${tidbfbconfig}
###############################################################################
###############################################################################
##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;;
    -RESTOREDB) CurOpt="-RESTOREDB";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME_P) declare primaryhostname="${inopt}";continue;;
    -HOSTNAME_S) declare standbyhostname="${inopt}";continue;;
    -RESTOREDB) declare restoredb="${inopt}";continue;;
    esac
done


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

function f_getbackpid
{
    f_PrintLog "Info" "Start to run f_getbackpid."
    if [ -f ${dumppidfile} ] 
    then
        echo "************************"
        ls -l  ${dumppidfile}
        cat ${dumppidfile}
        echo "************************"
        
        f_PrintLog "Info" "Start to read backup pid file ${dumppidfile}"
        source ${dumppidfile}  
    else
        f_PrintLog "Error" "Can not find backup pid file ${dumppidfile}, exit!!!"
        exit 1
    fi

}


function f_checkdrainertso
{
    f_PrintLog "Info" "Start to run f_checkdrainertso."
    f_get_committs 
    if [ "${TIDBIP}" = "${tidbIp}" -a "${CHECKPOINTCOMMITTM}" = "${cmt_ts}" -a "${CHECKPOINTCOMMITTSO}" = "${cmt_tso}" ]
    then
        f_PrintLog "Info" "Drainer check pass, checkpoint tso matched."
    else
        f_PrintLog "Error" "Drainer check failed, pls check config file ${dumppidfile}."
        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_revoke_appuser
{
    f_PrintLog "Info" "Start to run f_revoke_appuser."
    f_PrintLog "Info" "list appuser grants scripts."
    ls -l ${WorkDir}/appuser*.sql

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

function f_grant_repl
{
    f_PrintLog "Info" "Start to run f_grant_repl."
    f_PrintLog "Info" "repl grants before grant..."
    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 grant Insert,Update,Delete,Create,Drop,Alter,Execute,Index on *.* to repl@'%'"
    mysql --login-path=${locallogin:-tidblogin} -e "grant Insert,Update,Delete,Create,Drop,Alter,Execute,Index on *.* to repl@'%'"
    local _rt_code=$?
    f_PrintLog "Info" "repl grants after grant..."
    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" "grant write privileges from repl successfully."
    else
        f_PrintLog "Error" "grant write privileges from repl failed, return:${_rt_code}."
        exit 1
    fi 
}

function f_dropdbcmd
{
    local _dropdb=$1
    f_PrintLog "Info" "Start to run f_dropdbcmd. $1"
    f_PrintLog "Info" "mysql --login-path=tidblogin -e drop database if exists ${_dropdb}"
    mysql --login-path=tidblogin -e "drop database if exists ${_dropdb}"
    return $?
}

function f_DropDatabase
{
    local _dbs=$1
    f_PrintLog "Info" "Start to run f_DropDatabase. $1"
    ls -l ${BAKDIR} | grep "schema-create.sql"
    backupdb=$(ls -l ${BAKDIR} | grep "schema-create.sql" | awk '{gsub("-schema-create.sql","",$NF);{printf "%s,",$NF}}')
    mysql --login-path=tidblogin -e "show databases"

    f_PrintLog "Info" "Databases to be droped: ${_dbs}, pls check!"
    f_PrintLog "Info" "Databases already backuped: ${backupdb}, pls check!"
    sleep 10

    local _dbs_list=$(echo "${_dbs}"| tr "," " ")
    for _db in ${_dbs_list}
    do
        _db_flag=$(echo "${backupdb}" | grep -w "${_db}" |wc -l)
        if [ ${_db_flag} -eq 0 ]
        then
            f_PrintLog "Warn" "Database ${_db} not in backup list:${backupdb}, skip drop!"
            sleep 5
            continue
        fi
        f_dropdbcmd "${_db}"
        local _rt_code=$?
        if [ ${_rt_code} -eq 0 ]
        then
            f_PrintLog "Info" "drop database ${_db} successful!"
        else
            f_PrintLog "Error" "drop database ${_db} failed, return code:${_rt_code}!"
        fi
        sleep 2
    done

    mysql --login-path=tidblogin -e "show databases"
    sleep 10
}

function f_checkconnection
{

    f_PrintLog "Info" "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 --login-path=${locallogin:-tidblogin}  -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 --login-path=${locallogin:-tidblogin} -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

    app_counts=$(wc ${tmp_file}|awk '{printf "%d",$1+$2}')
    if [ ${app_counts:-2} -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
}

function f_CheckDumplingResult
{
    _baklog=$1
    f_PrintLog "Info" "Start to run f_CheckDumplingResult. $1"
    
    bak_succ=$(tail ${_baklog} | grep "dump data successfully"|wc -l)
    bak_err=$(awk '{if($4=="[ERROR]"){e++}};END{print e}' ${_baklog} 2>/dev/null)
    ls -l ${_baklog}
    echo "############################################################"
    head ${_baklog}
    echo "..."
    tail ${_baklog}
    echo "############################################################"
    if [ ${bak_succ:-0} -ge 1 -a ${bak_err:-0} -eq 0 ]
    then
        f_PrintLog "Info" "Dumpling backup finish, continue."
    else
        f_PrintLog "error" "Dumpling backup failed, pls check backup log ${_baklog}."
        exit 1
    fi

}



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

    # 
    f_CheckLightningCount
    f_runlightning 
}


###################
####    Main   ####
###################
function f_fb_standby_lightning_main
{
    #检查集群没有连接
    #判断checkpoint表的状态为复制停止状态，而且committs跟备份能对齐
    #执行全库导入

    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}')
    tidbIp="${localIp}"

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

    # 获取集群信息
    # 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

    # 获取备份配置文件
    f_getbackpid 

    # 检查dumpling备份结果
    f_CheckDumplingResult "${LOGFILE}"

    # 回收应用用户权限
    f_revoke_appuser

    # 检查应用连接
    tmp_file="${LogDir}/tmp_apps.txt"
    echo "" > ${tmp_file}
    f_checkconnection

    # drop数据库
    if [ -z "${restoredb}" ]
    then
        # drop all databases
        restoredb=$(mysql --login-path=tidblogin -NBe "select group_concat(SCHEMA_NAME separator ',') from INFORMATION_SCHEMA.SCHEMATA where SCHEMA_NAME not in ('INFORMATION_SCHEMA','METRICS_SCHEMA','PERFORMANCE_SCHEMA','mysql') ")
    fi
    f_DropDatabase "${restoredb}"

    # 执行恢复
    f_lightningmain

    # 检查drianer checkpoint状态
    f_checkdrainertso

    # 授予repl用户权限
    f_grant_repl

    f_PrintLog "Succ" "Run function f_fb_standby_lightning_main finish!"
    f_PrintLog "Info" "Successful to run Script ${ShellName} on ${HostName}, script_base_name ${script_base_name}."
    exit 0
}


 
f_fb_standby_lightning_main

