#!/bin/env bash
##Description: clean drainer checkpoint 

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "bash ${ShellName}  [-hostname <hostname>]"
    echo "  [-ip <ip>] [-port <port>] [-user <user>] [-passwd <passwd>]  "
    echo "  [-standbyip <ip>] [-standbyport <port>] [-standbyuser <user>] [-standbypasswd <passwd>]  "
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -standbyip 172.16.xxx -standbyport 4100 -standbyuser abcuser1 -standbypasswd xxx -checkpointschema ccb"
    exit 22
}

function f_PrintLog
{
    _LogFlag=$(echo "$1"|tr "a-z" "A-Z")
    [ $(echo "$1"|wc -L) -eq 4 ] && _LogFlag=$(echo "${_LogFlag}_")
    _LogMessage=$2
    # declare LogFile="${LogFile:-"/tmp/${PShellName:-${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
}


###############################################################################
##Init##
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};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;;
    -STANDBYIP|-IP) CurOpt="-STANDBYIP";continue;;
    -STANDBYPORT|-PORT) CurOpt="-STANDBYPORT";continue;;
    -STANDBYUSER|-USER) CurOpt="-STANDBYUSER";continue;;
    -STANDBYPASSWORD|-STANDBYPASSWD|-PASSWD) CurOpt="-STANDBYPASSWORD";continue;;
    -CHECKPOINTSCHEMA|-CKPSCHEMA) CurOpt="-CKPSCHEMA";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME) declare LocalHost="${inopt}";continue;;
    -STANDBYIP) declare s_ip="${inopt}";continue;;
    -STANDBYPORT) declare s_port="${inopt}";continue;;
    -STANDBYUSER) declare s_user="${inopt}";continue;;
    -STANDBYPASSWORD) declare s_passwd="${inopt}";continue;;
    -CKPSCHEMA) declare c_schema="${inopt}";continue;;
    esac
done

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


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

    f_PrintLog "Info" "start to run sql:${_execsql}"
    exec_result=$(mysql -h${_ip} -P${_port} -u${_user} -p${_passwd} -NBe "${_execsql}")
}


function f_committs_stop
{
    f_PrintLog "Info" "Start to run f_committs_diff."
    #最多检查3次,每次间隔10s
    for i in 1 2 3 
    do
        #commit ts
        ck_sql="select checkPoint from ${c_schema}.checkpoint"
        f_runsql "${s_ip}" "${s_port}" "${s_user}" "${s_passwd}" "${ck_sql}"
        if [ $? -ne 0 ]
        then
            f_PrintLog "Error" "run check sql failed, STMT:${ck_sql}, pls check!!!"
            exit 1
        fi

        cmt_ts=$(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
        
        #time-tso diff
        ck_sql="SELECT timestampdiff(SECOND,TIDB_PARSE_TSO(${cmt_ts}),NOW()) "
        f_runsql "${s_ip}" "${s_port}" "${s_user}" "${s_passwd}" "${ck_sql}"
        f_PrintLog "Info" "Drainer checkpoint consistent is ${consistent} (should be true), commitTS is ${cmt_ts}, is ${exec_result} (should>30) seconds away from now!"
        
        [ ${exec_result} -gt 30 -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
{
    #在主集群执行建表和写入数据,去目标集群查询数据
    f_PrintLog "Info" "Start to run f_drop_checkpoint."
    #sql
    drop_tab="drop table ${c_schema}.checkpoint"
    select_tab="select * from ${c_schema}.checkpoint"
    
    #Primary
    f_runsqlstmt "${s_ip}" "${s_port}" "${s_user}" "${s_passwd}"  "${select_tab}"
    f_runsqlstmt "${s_ip}" "${s_port}" "${s_user}" "${s_passwd}"  "${drop_tab}"

    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "exec sql failed, stmt: ${select_tab}"
        exit 1
    fi
}


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

#1. 写入数据,确认复制状态
#1. 确认 cluster_b 上 drainer 断点表中 binlog commitTS 与 cluster_b tso 时间差小于 30s; 
#2. tsmap 在两分钟之内不再变化
#方案二：上有写测试数据，观测下游是否消费
function clean_main
{

[ -z "${c_schema}" ] && c_schema="tidb_binlog"

f_committs_stop

f_drop_checkpoint
f_PrintLog "Info" "Drop table ${c_schema}.checkpoint finish."

}

clean_main | tee -a ${LogFile:-"/tmp/${PShellName:-${ShellName}}.log"}
exit ${PIPESTATUS[0]}
