#!/bin/env bash
#9_tiup_slave_deploy.sh

#1.打包本地.tiup目录
#2.部署tiup备节点
#3.执行pprof脚本
#4.纳管配置文件

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "Syntax:"
    echo "bash ${ShellName} "
    echo " -slaveip <172.16.11.58>"
    echo " "
    echo " #Description:"
    echo " -slaveip ,the tiup slave host ip"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -slaveip 172.16.11.58 " 
    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}_")
    
    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

    [ "${_LogFlag}" = "ERROR" ] && exit 11 || return 0
}

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



function f_tiup_primary
{
    f_PrintLog "Debug" "Start to run function f_tiup_primary"
    local _node=$1

    dt=$(date "+%Y%m%d")
    cd ${TidbHome}

    f_PrintLog "Info" "cd $(pwd);tar -czf tiup.${dt}.tar.gz .tiup"
    tar -czf tiup.${dt}.tar.gz .tiup
    local _rt_code=$?
    ls -l tiup.${dt}.tar.gz

    if [ ${_rt_code} -eq 0 -a -f "tiup.${dt}.tar.gz" ]
    then
        f_PrintLog "Info" "Create tiup tar file successfully, scp to slave host."
    else
        f_PrintLog "Error" "Create tiup tar file failed, return:${_rt_code}."
        exit 1
    fi 

    f_PrintLog "Info" "tiup cluster push ${clsName} ${TidbHome}/tiup.${dt}.tar.gz ${TidbHome}/tiup.${dt}.tar.gz -N${_node}"
    # tiup cluster push ${clsName} ${TidbHome}/tiup.${dt}.tar.gz ${TidbHome}/tiup.${dt}.tar.gz -N${_node}
    local sshkey="${TidbHome}/.tiup/storage/cluster/clusters/${clsName}/ssh/id_rsa"
    f_PrintLog "Info" "local tidb home before scp..."
    ssh -i ${sshkey} tidb@${_node%:*} "ls -la ${TidbHome}"
    f_PrintLog "Info" "scp -i ${sshkey} tiup.${dt}.tar.gz tidb@${_node%:*}:${TidbHome}/tiup.${dt}.tar.gz"
    scp -i ${sshkey} tiup.${dt}.tar.gz tidb@${_node%:*}:${TidbHome}/tiup.${dt}.tar.gz
    f_PrintLog "Info" "remote tidb home after scp..."
    ssh -i ${sshkey} tidb@${_node%:*} "ls -la ${TidbHome}"

    # rm -f tiup.${dt}.tar.gz

}

function f_tiup_standby
{
    f_PrintLog "Debug" "Start to run function f_tiup_standby"
    local _node=$1
    local sshkey="${TidbHome}/.tiup/storage/cluster/clusters/${clsName}/ssh/id_rsa"
    f_PrintLog "Info" "remote tidb home before unzip..."
    ssh -i ${sshkey} tidb@${_node%:*} "ls -la ${TidbHome}"
    f_PrintLog "Info" "ssh -i ${sshkey} tidb@${_node%:*} cd ${TidbHome};tar -zxf tiup.${dt}.tar.gz"
    ssh -i ${sshkey} tidb@${_node%:*} "cd ${TidbHome};tar -zxf tiup.${dt}.tar.gz"
    f_PrintLog "Info" "remote tidb home after unzip..."
    ssh -i ${sshkey} tidb@${_node%:*} "ls -la ${TidbHome}"
}

function f_wget
{
    f_PrintLog "Debug" "Start to run function f_wget $2"
    local _dir=$1
    local _file=$2

    [ ! -d ${_dir} ] && mkdir -p ${_dir}

    if [ -f ${_dir}/${_file} ]
    then
        f_PrintLog "Info" "File ${_dir}/${_file} already exist, not need wget."
        ls -l ${_dir}/${_file}
    else
        f_PrintLog "Info" "wget ${TIUP_WGET_REPO}/${_file} -P ${_dir} --timeout=30 --tries=3"
        wget ${TIUP_WGET_REPO}/${_file} -P ${_dir} --timeout=30 --tries=3
        if [ $? -eq 0 -a -f ${_dir}/${_file} ] 
        then
            f_PrintLog "Succ" "Download ${_dir}/${_file} successfully."
            ls -l ${_dir}/${_file}
        else
            f_PrintLog "Error" "Download ${_dir}/${_file} failed!!!"
            # touch ${_dir}/${_file}
            rm -f ${_dir}/${_file}
            exit 1
        fi
    fi
}

function f_generate_tidb_config
{
    f_PrintLog "Debug" "Start to run function f_generate_tidb_config"
    ls -l ${TidbHome}/tidb-deploy/
    if [ -f ${TidbHome}/tidb-deploy/tidb.conf ]
    then
        f_PrintLog "Info" "tidb config file already exist. start to check file content."
        cat ${TidbHome}/tidb-deploy/tidb.conf 
        tidb_cls0=$(tail -1 ${TidbHome}/tidb-deploy/tidb.conf|awk '{printf "%s %s %s",$1,$2,$3}')
        tidb_cls1=$(tiup cluster list |awk '{if($3~"v" && $4~"tiup"){printf "%s %s %s",$1,$2,$3}')
        if [ "${tidb_cls0}" = "${tidb_cls1}" ]
        then
            f_PrintLog "Info" "tidb config file already exist, check pass, quit!"
            ls -l ${TidbHome}/tidb-deploy/tidb.conf 
            return 0
        else
            f_PrintLog "Info" "tidb config file exist, but data is wrong, rm it!"
            ls -l ${TidbHome}/tidb-deploy/tidb.conf
            cat ${TidbHome}/tidb-deploy/tidb.conf
            rm -f ${TidbHome}/tidb-deploy/tidb.conf
        fi
    fi

    f_PrintLog "Info" "Start to generate tidb config file ${TidbHome}/tidb-deploy/tidb.conf"
    tiup cluster list > ${TidbHome}/tidb-deploy/tidb.conf
    cat /home/db/tidb/tidb-deploy/tidb.conf

}

###############################################################################
##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};chmod ugo+rwx ${LogDir} 2>/dev/null;
RunTs=$(date "+%Y%m%d.%H%M%S")
LogFile="${LogDir}/${ShellName}.${RunTs}.log";
touch ${LogFile} 2>/dev/null;chmod ugo+rw "${LogFile}" 2>/dev/null;
Shellcksum=$(cksum ${WorkDir%/}/${ShellName} 2>/dev/null|awk '{printf "%d",$1}')
CpuHardware=$(uname -m);CpuType=$(uname -p);OSType=$(uname -s)
declare -i UserID=$(id -u);declare UserName=$(whoami);declare HostName=$(hostname);
###############################################################################
##TiDB Var##
TidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
CLSVERSION=""
TIUP_MIRROR=""

if [ "${HostName:0:1}" = "n" -o "${HostName:0:2}" = "wn" ]
then
    # TIUP_WGET_REPO="https://tiup-mirrors.pingcap.com"
else
    # TIUP_WGET_REPO="https://tiup-mirrors.pingcap.com"
fi
###############################################################################
###############################################################################
##Get inopt
# [ -z "${ShellOption}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -CLUSTER|-CLS) CurOpt="-CLUSTER";continue;;
    -SLAVEIP|-S) CurOpt="-SLAVEIP";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -SLAVEIP) declare slaveip="${inopt}";continue;;
    -CLUSTER) declare clsname="${inopt}";continue;;
    esac
done

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

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

function pprof_main
{
    f_PrintLog "Debug" "Start to run function f_pprof"
    
    if [ ! -f "${TidbHome}/scripts/tidb_pprof_fix.sh" ]
    then
        f_PrintLog "Warn" "${TidbHome}/scripts/tidb_pprof_fix.sh script not exist, start wget !"
        f_wget "${TidbHome}/scripts"  tidb_pprof_fix.py
    fi

    sh ${TidbHome}/scripts/tidb_pprof_fix.sh
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "Run script tidb_pprof_fix.sh failed, pls check!!!"
        exit 1
    fi

    f_PrintLog "Info" "iptables -nL before update..."
    iptables -nL
    sh ${TidbHome}/scripts/tidbiptables.sh
    if [ $? -ne 0 ]
    then
        f_PrintLog "Error" "Run script idbiptables.sh failed, pls check!!!"
        exit 1
    fi
    f_PrintLog "Info" "iptables -nL after update..."
    iptables -nL
    f_PrintLog "Succ" "Run function pprof_main finish!"
}

function tidbconfig_main
{
    f_PrintLog "Debug" "Start to run function tidbconfig_main"
    
    f_generate_tidb_config
    if [ -f ${TidbHome}/tidb-deploy/tidb.conf ]
    then
        f_PrintLog "Info" "Send tidb config file ${TidbHome}/tidb-deploy/tidb.conf to other node."
        f_PrintLog "Info" "tiup cluster push ${clsName} ${TidbHome}/tidb-deploy/tidb.conf ${TidbHome}/tidb-deploy/tidb.conf"

        tiup cluster push ${clsName} ${TidbHome}/tidb-deploy/tidb.conf ${TidbHome}/tidb-deploy/tidb.conf
        if [ $? -ne 0 ]
        then
            f_PrintLog "Error" "tiup push file failed, file:${TidbHome}/tidb-deploy/tidb.conf"
            exit 1
        else
            f_PrintLog "Info" "tiup push file finish, file:${TidbHome}/tidb-deploy/tidb.conf"
        fi
    else
        f_PrintLog "Error" "Tidb config ${TidbHome}/tidb-deploy/tidb.conf not exist, pls check!!!"
        exit 1
    fi

    f_PrintLog "Succ" "Run function tidbconfig_main finish!"
}

function tiup_slave_main
{
    # HA role: primary or standby 

    if [ ${UserID} -eq 0 ]
    then
        pprof_main

        # run with tidb
        f_PrintLog "Debug" "su tidb -c sh ${WorkDir}/${ShellName} \"${ShellOption}\""
        su tidb -c "sh ${WorkDir}/${ShellName} ${ShellOption}" || exit $?
    elif [ "${UserName}" = "tidb" ]
    then
        # use tidb user
        source ${TidbHome}/.bash_profile

        # check cluster name 
        if [ -z "${clsname}" ]
        then
            clsName=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
        else
            clsName=$(tiup cluster list 2>/dev/null|awk -v cn="${clsname}"  '{if($1==cn){printf "%s\n",$1;exit}}') 
        fi

        if [ -z "${clsName}" ]
        then
            f_PrintLog "Error"  "Cluster ${clsname} not exist, pls check cluster name, quit!!!"
            exit 1
        fi

        # get remote slave tiup node
        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}}')

        promethues_ip=$(tiup cluster display ${clsName} 2>/dev/null|awk '{
        if($2=="tikv"){printf "%s ",$3}
        }')

        for prom in ${promethues_ip}
        do
            ip_flag=$(echo "${IPList}" |grep -w "${prom}" |wc -l)
            if [ ${ip_flag} -eq 0 ]
            then
                slaveip="${prom}"
                f_PrintLog "Info" "Get slaveip ${slaveip}"
                break
            fi
        done

        tiup cluster display ${clsName}

        slavenode=$(tiup cluster display ${clsName}  2>/dev/null | awk -v id="${slaveip}:" '{
        if($1~id && $6~"Up" ){printf "%s",$1;exit}}')
        
        f_tiup_primary "${slavenode}"
        f_tiup_standby "${slavenode}"

        tidbconfig_main
    else
        f_PrintLog "Error" "Pls run script with user root or tidb, exit!!!"
    fi

    f_PrintLog "Succ" "Run function tiup_slave_main finish!"
}


tiup_slave_main

