#!/bin/env bash
#3_tidb_deploy_cluster.sh

#1.检查集群部署yaml配置文件
#2.执行集群部署和初始化
#3.修改root的初始密码

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "Syntax:"
    echo "bash ${ShellName} "
    echo "-rootpswd <123456> "
    echo " "
    echo " #Description:"
    echo " -rootpswd ,the root passwd "
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -rootpswd 123456 " 
    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
}

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


###############################################################################
##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)
YAMLPATH="${TidbHome}/scripts"
CLSVERSION=""
###############################################################################
###############################################################################
##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;;
    -VERSION|-CLSVERSION) CurOpt="-VERSION";continue;;
    -TOPOLOGY|-T) CurOpt="-TOPOLOGY";continue;;
    -ROOTSSHIDFILE|-I) CurOpt="-ROOTSSHIDFILE";continue;;
    -ROOTPSWD|-P) CurOpt="-ROOTPSWD";continue;;
    -SKIPCHECK|--SKIPCHECK) declare SKIPCHECK="yes";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -CLUSTER) declare clsname="${inopt}";continue;;
    -VERSION) declare clsversion="${inopt}";continue;;
    -TOPOLOGY) declare clstopology="${inopt}";continue;;
    -ROOTSSHIDFILE) declare rootsshid="${inopt}";continue;;
    -ROOTPSWD) declare rootpswd="${inopt}";continue;;
    esac
done

f_PrintLog "Info" "Start to run Script ${ShellName}, the Shellcksum is ${Shellcksum}"
f_PrintLog "Info" "Script Options:${ShellOption}"
[ -z "${rootpswd}" ] && f_syntax;
###############################################################################
####Main####

function f_ClusterCheck_main
{
    f_PrintLog "Debug" "Start to run Script f_ClusterCheck_main"
    if [ ! -f "${YAMLPATH}/${clstopology}" ]
    then
        f_PrintLog "Error" "Topology file ${YAMLPATH}/${clstopology} not exist, pls check, exit!!!"
        exit 1
    fi

    f_PrintLog "Debug" "tiup cluster check ${YAMLPATH}/${clstopology} -uroot  -p"

    expect -c "
        spawn tiup cluster check ${YAMLPATH}/${clstopology} -uroot -p 
        expect -nocase \"Input SSH password:\" {send \"$rootpswd\r\"}
        interact
    " > /tmp/tiupcheck.${clsname}.${RunTs}.log 2>&1

    # tiup cluster check ${clstopology} -uroot -p > /tmp/tiupcheck.${clsname}.${RunTs}.log 2>&1
    _rt_code=$?
    _err=$(grep "Error" /tmp/tiupcheck.${clsname}.${RunTs}.log | grep -v "numalctl" | wc -l)
    _warn=$(grep "Warn" /tmp/tiupcheck.${clsname}.${RunTs}.log | grep -v "numalctl" | wc -l)
    _pass=$(grep "Pass" /tmp/tiupcheck.${clsname}.${RunTs}.log | wc -l)
 
    if [ ${_rt_code} -eq 0 -a ${_err} -eq 0 -a ${_warn} -eq 0 -a ${_pass} -gt 1 ]
    then
        f_PrintLog "Info"  "Tiup Check Result:  Rtcode:${_rt_code}, Error:${_err}, Warn:${_warn}, Pass:${_pass}"
        f_PrintLog "Info"  "tiup cluster check successful. Log file /tmp/tiupcheck.${clsname}.${RunTs}.log, Yaml conifg:${YAMLPATH}/${clstopology}"
    else
        f_PrintLog "Info"  "Tiup Check Result:  Rtcode:${_rt_code}, Error:${_err}, Warn:${_warn}, Pass:${_pass}"
        f_PrintLog "Error"  "tiup cluster check failed. Pls check log file /tmp/tiupcheck.${clsname}.${RunTs}.log, Yaml conifg:${YAMLPATH}/${clstopology}"
    fi
}


function f_ClusterDeploy_main
{
    f_PrintLog "Debug" "Start to run Script f_ClusterDeploy_main"
    tiup cluster list
    f_PrintLog "Debug" "tiup cluster deploy ${clsname}  ${clsversion} ${YAMLPATH}/${clstopology} -uroot -p --yes"

    expect -c "
        spawn tiup cluster deploy ${clsname}  ${clsversion} ${YAMLPATH}/${clstopology} -uroot -p --yes 
        expect -nocase \"Input SSH password:\" {send \"$rootpswd\r\"}
        interact
    "  > /tmp/tiupdeploy.${clsname}.${RunTs}.log 2>&1

    # tiup cluster deploy ${clsname}  ${clsversion} ${clstopology} -uroot  -p --yes > /tmp/tiupdeploy.${clsname}.${RunTs}.log 2>&1
    _rt_code=$?
    _err=$(grep -i "error" /tmp/tiupdeploy.${clsname}.${RunTs}.log | wc -l)
    _fail=$(grep -i "fail" /tmp/tiupdeploy.${clsname}.${RunTs}.log | grep -v "numalctl" | wc -l)
    _done=$(grep -i "done" /tmp/tiupdeploy.${clsname}.${RunTs}.log | wc -l)
    _succ=$(grep -i "deployed successfully" /tmp/tiupdeploy.${clsname}.${RunTs}.log | wc -l)
    f_PrintLog "Info"  "Tiup Check Result:  Rtcode:${_rt_code}, Error:${_err}, Fail:${_fail}, Done:${_done}, Succ:${_done}"

    tiup cluster list 
    clsName=$(tiup cluster list 2>/dev/null|awk -v cn="${clsname}" -v cv="${clsversion}" '{if($1==cn && $3==cv){printf "%s\n",$1;exit}}') 

    if [ ${_rt_code} -eq 0 -a ${_succ} -eq 1 -a ${_err} -eq 0 -a ${_fail} -eq 0 -a "${clsName}" = "${clsname}" ]
    then
        tiup cluster display ${clsname}
        f_PrintLog "Info"  "Cluster ${clsname} deploy successful."
    else
        f_PrintLog "Error"  "Cluster ${clsname} deploy failed."
    fi
}



function deploy_main
{
    if [ ${UserID} -eq 0 ]
    then
        # 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
        ls -l ${YAMLPATH}

        # default var
        clstopology=$(ls -lt ${YAMLPATH}| awk '{if($NF~"yaml"){printf "%s",$NF;exit}}')
        clsname=${clstopology%.*}
        clsversion=${CLSVERSION}
        f_PrintLog "Info" "Deploy parameter clstopology:${clstopology} clsname:${clsname} clsversion:${clsversion}"

        if [ -z "${clstopology}" -o -z "${clsname}" -o -z "${clsversion}" ]
        then
            f_PrintLog "Error" "Deploy parameter check failed, pls check the yaml file!!!"
            exit 1
        fi

        # check cluster name 
        clsName=$(tiup cluster list 2>/dev/null|awk -v cn="${clsname}"  '{if($1==cn){printf "%s\n",$1;exit}}') 
        if [ "${clsName}" = "${clsname}" ]
        then
            f_PrintLog "Info"  "Cluster ${clsname} already exist, quit!"
            tiup cluster display ${clsname}
            exit 0
        fi

        [ "${SKIPCHECK:-no}" = "no" ] && f_ClusterCheck_main
        f_ClusterDeploy_main
        
    else
        f_PrintLog "Error" "Pls run script with user root or tidb, exit!!!"
    fi

    f_PrintLog "Succ" "Run script ${ShellName} finish!"
}


deploy_main
