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

script_base_name="tidb_fb_primary_startrepl"


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 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}";
    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_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 [ -n "$(echo "${drainer_status:-Up}" | grep -v "Up")" ]
    then
        f_PrintLog "Error" "drainer status check failed. drainer status is ${tidbDrainerId}:${drainer_status}"
        exit 1
        # [ "${HostRole}" = "PRIMARY" ] && 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_startnode
{
    f_PrintLog "Info" "Start to run f_startnode. $1"
    _nodeid=$1
    local _node_status1=$(tiup cluster display ${clsName}  2>/dev/null |awk -v dip="${_nodeid}" '{
        if($1==dip){printf "%s",$6;exit}
        }')

    f_PrintLog "Info" "tiup cluster start ${clsName} -N${_nodeid} --yes"
    tiup cluster start ${clsName} -N${_nodeid} --yes
    local _rt_code=$?
    sleep 10
    local _node_status2=$(tiup cluster display ${clsName}  2>/dev/null |awk -v dip="${_nodeid}" '{
        if($1==dip){printf "%s",$6;exit}
        }')

    if [ ${_rt_code} -eq 0 -a "${_node_status2}" == "Up" ]
    then
        f_PrintLog "Info" "Node ${_nodeid} start successfully, status ${_node_status1}->${_node_status2}."
    else
        f_PrintLog "Error" "Node ${_nodeid} start failed, return code:${_rt_code}, status ${_node_status1}->${_node_status2}."
        exit 1
    fi
}

    
###############################################################################
##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=""
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;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME_P) declare primaryhostname="${inopt}";continue;;
    -HOSTNAME_S) declare standbyhostname="${inopt}";continue;;
    esac
done

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

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

function f_check_fb_config
{
    f_PrintLog "Info" "Start to run f_check_fb_config."
    # clsname,connip,connport,dbsize,dbs,userlist,drainernode,backupdir,repluser
    clsName=$(tiup cluster list 2>/dev/null|awk -v cn="${PRIMARYCLUSTERNAME}" '{if($1==cn){printf "%s\n",$1;exit}}') 
    if [ -n "${clsName}" ]
    then
        f_PrintLog "Info" "Config file, PRIMARYCLUSTERNAME:${PRIMARYCLUSTERNAME}, check pass!"
    else
        f_PrintLog "Error" "Config file, PRIMARYCLUSTERNAME:${PRIMARYCLUSTERNAME} not exist, check failed!"
        exit 1
    fi

    f_PrintLog "Info" "find valid cluster name is ${clsName}"
    tiup cluster display ${clsName} 

    drNodeid=$(tiup cluster display ${clsName} 2>/dev/null|awk -v nd="${STANDBYIP}" '{if($1~nd && $2=="drainer"){printf "%s\n",$1;exit}}')
    if [ -n "${drNodeid}" ]
    then
        f_PrintLog "Info" "Config file, STANDBYIP:${STANDBYIP}, check pass!"
    else
        f_PrintLog "Error" "Config file, DRAINERIP:${STANDBYIP}  not exist, check failed!"
        exit 1
    fi
    
    ysdt=$(date -d 'yesterday' +%Y%m%d)
    curdt=$(date +%Y%m%d)
    RUNDT=${PRIMARYRUNTIME%.*}
    if [ ${RUNDT} -ge ${ysdt} -a ${RUNDT} -le ${curdt} ]
    then
        f_PrintLog "Info" "Config file, RUNTIME:${PRIMARYRUNTIME}, check pass!"
    else
        f_PrintLog "Error" "Invalid config file, RUNTIME:${PRIMARYRUNTIME} older then yesterday, check failed!"
        exit 1
    fi

    f_PrintLog "Info" "Check config info finished. clsname:${clsName}, remote drainerId:${drNodeid}, runTime:${PRIMARYRUNTIME}"
}

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

}

function f_startrepl_main
{
    f_PrintLog "Info" "Start to run f_startrepl_main."
    f_PrintLog "Info" "Cluster status before start..."
    tiup cluster display ${clsName}  2>/dev/null
    drStatus1=$(tiup cluster display ${clsName}  2>/dev/null| awk -v dr="${drNodeid}" '{if($1==dr){printf "%s\n",$6;exit}}')

    f_startnode "${drNodeid}"

    f_PrintLog "Info" "Cluster status after start..."
    tiup cluster display ${clsName}  2>/dev/null

}

###################
####    Main   ####
###################
function f_fb_primary_startrepl_main
{
    #检查切换配置文件
    if [ -f ${tidbfbconfig} ]
    then
        source ${tidbfbconfig}
        f_PrintLog "Info" "Get cluster info finished. PRIMARYRUNTIME:${PRIMARYRUNTIME}, PRIMARYHOSTNAME:${PRIMARYHOSTNAME}, PRIMARYCLUSTERNAME:${PRIMARYCLUSTERNAME}, STANDBYIP:${STANDBYIP}"
        f_check_fb_config
    else
        f_PrintLog "Error" "Can not find config file ${tidbfbconfig}, quit!!!"
        exit 1
    fi
    
        f_PrintLog "Info" "Check config info finished. clsname:${clsName}, remote drainerId:${drNodeid}, runTime:${PRIMARYRUNTIME}"

    #主节点binlog状态正常
    f_checkrepl_main 
    
    #启动主备复制
    f_startrepl_main

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

f_fb_primary_startrepl_main
# exit ${PIPESTATUS[0]} 


