#!/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 " "
    echo " #Description:"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName}  " 
    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_runsql
{
    _connstr=$1
    _pswd=$2
    _stmt=$3
    # f_PrintLog "Info" "START TO RUN SQL STMT:${_stmt}, DBinfo:${_connstr}"
    runSTMT=$(mysql ${_connstr}${_pswd} -NBe "${_stmt}")
    _rt_code=$?
    if [ $_rt_code -ne 0 ]
    then
        f_PrintLog "Error" "Run stmt failed, exit"
        exit 1
    else
        echo ${runSTMT}
    fi

}

function f_setpswd
{
    f_PrintLog "Debug" "Start to run Script f_Setpswd"
    _clsname=$1

    tidb_pswd=$(grep "The new password is" /tmp/tiupinit.${_clsname}.${RunTs}.log |awk -F: '{gsub("\\.$","",$2);gsub("[ \047]","",$2);printf "%s\n",$2;exit}')
    # cat /tmp/tiupinit.log |grep "The new password is"|awk -F: '{gsub("\\.$","",$2);gsub("[ \047]","",$2);printf "%s\n",$2}'
    DB_MYROOT_PASSWD=`echo "" |base64 -d`


    tiup cluster display ${_clsname} 
    tidb_id=$(tiup cluster display ${_clsname} 2>/dev/null|awk '{if($2=="tidb")printf "%s ",$1}')

    tidb_ip=${tidb_id%:*}
    tidb_port=${tidb_id#*:}
    tidb_stmt="select user()"
    tidb_connstr="-h${tidb_ip} -P${tidb_port} -uroot -p"

    f_PrintLog "Debug" "START TO RUN SQL STMT:${tidb_stmt}, DBinfo:${tidb_connstr}"
    connOk=$(f_runsql "${tidb_connstr}" "${tidb_pswd:-123}" "${tidb_stmt}")
    if [ "${connOk%@*}" = "root" ]
    then
        f_PrintLog "Info" "Connect db successfully, connect user:${connOk}."
    else
        f_PrintLog "Error" "Run stmt ${tidb_stmt} failed! quit!!!"
        exit 1
    fi

    f_PrintLog "Info" "Start to update root passwd."
    tidb_stmt="set password for 'root'@'%'='${DB_MYROOT_PASSWD}';FLUSH PRIVILEGES;"
    f_PrintLog "Debug" "START TO RUN SQL STMT:set password for 'root'@'%'='';FLUSH PRIVILEGES;, DBinfo:${tidb_connstr}"
    f_runsql "${tidb_connstr}" "${tidb_pswd:-123}" "${tidb_stmt}"

    tidb_stmt="select user()"
    f_PrintLog "Debug" "START TO RUN SQL STMT:${tidb_stmt}, DBinfo:${tidb_connstr}"
    connOk=$(f_runsql "${tidb_connstr}" "${DB_MYROOT_PASSWD:-123}" "${tidb_stmt}")
    if [ "${connOk%@*}" = "root" ]
    then
        f_PrintLog "Info" "Connect db with new passwd successfully, connect user:${connOk}."
        f_PrintLog "Info" "Root password update successfully."
    else
        f_PrintLog "Error" "Run stmt ${tidb_stmt} with new passwd failed, Root password update failed! quit!!!"
        exit 1
    fi
}

###############################################################################
##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=""
###############################################################################
###############################################################################
##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;;
#     -HELP|--HELP|-H) f_syntax;;
#     -*) CurOpt="";continue;;
#     esac
#     case "${CurOpt}" in
#     -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 f_ClusterInit_main
{
    f_PrintLog "Debug" "Start to run Script f_ClusterInit_main"
    _clsname=$1
#     Started cluster `n-prd` successfully
# The root password of TiDB database has been changed.
# The new password is: '96%Lb270^a8W+Uesc&'.
# Copy and record it to somewhere safe, it is only displayed once, and will not be stored.
# The generated password can NOT be get and shown again.
    f_PrintLog "Debug" "tiup cluster start ${_clsname} --init "
    tiup cluster start ${_clsname} --init  > /tmp/tiupinit.${_clsname}.${RunTs}.log 2>&1
    _rt_code=$?
    sleep 10
    _err=$(grep -i "error" /tmp/tiupinit.${_clsname}.${RunTs}.log | wc -l)
    _fail=$(grep -i "fail" /tmp/tiupinit.${_clsname}.${RunTs}.log | wc -l)
    _succ=$(grep -i "successfully" /tmp/tiupinit.${_clsname}.${RunTs}.log | wc -l)
    f_PrintLog "Info"  "Tiup Init Result:  Rtcode:${_rt_code}, Error:${_err}, Fail:${_fail}, Succ:${_done}"

    if [ ${_rt_code} -eq 0 -a ${_succ} -ge 1 -a ${_err} -eq 0 -a ${_fail} -eq 0 ]
    then
        tiup cluster display ${_clsname}
        f_PrintLog "Info"  "Cluster ${_clsname} init successful."
    else
        f_PrintLog "Error"  "Cluster ${_clsname} init failed, pls check log  /tmp/tiupinit.${_clsname}.${RunTs}.log"
        exit 1
    fi

    sleep 10
    f_setpswd ${_clsname}
}


function init_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

        # check cluster name 
        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"  "Cluster not exist, quit!"
            exit 1
        fi

        tiup cluster display ${clsName}       
        f_ClusterInit_main ${clsName} 
    else
        f_PrintLog "Error" "Pls run script with user root or tidb, exit!!!"
    fi

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


init_main
