#!/bin/env bash
#5_tidb_create_mgruser.sh

#1.关闭tiup telemetry
#2.关闭tidb telemetry
#3.部署tidb ctl工具

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "Syntax:"
    echo "bash ${ShellName} "
    echo "-cluster <n-prd> "
    echo "-version <v5.4.1> "
    echo " "
    echo " #Description:"
    echo " -cluster ,the tidb cluster name"
    echo " -version ,the tidb cluster version"
    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_disable_telemetry
{
    f_PrintLog "Debug" "Start to run function f_disable_telemetry"
    f_PrintLog "Info" "tiup telemetry before update..."
    tiup telemetry status
    tiup telemetry disable
    f_PrintLog "Info" "tiup telemetry after update..."
    tiup telemetry status
    tiup_flag=$(tiup telemetry status | grep status| awk '{print $2}')

    f_PrintLog "Info" "tidb telemetry before update..."
    mysql --login-path=-e "show variables like '%telemetry%'"
    mysql --login-path=-e "set global tidb_enable_telemetry = OFF"

    f_PrintLog "Info" "tidb telemetry after update..."
    mysql --login-path=-e "show variables like '%telemetry%'"

    tidb_flag=$(mysql --login-path=-NBe " show variables like '%telemetry%'"|awk '{printf "%s",$2}')

    if [ "${tiup_flag}" = "disable" -a "${tidb_flag}" =  "OFF" ]
    then
        f_PrintLog "Succ" "Disable telemetry successfully, tiup:${tiup_flag} tidb:${tidb_flag}."
    else
        f_PrintLog "Error" "Disable telemetry failed, tiup:${tiup_flag} tidb:${tidb_flag} !!!"
        exit 1
    fi
}

function f_deploy_tools
{
    f_PrintLog "Debug" "Start to run function f_deploy_tools"
    if [ -z "${clsversion}" ] 
    then
        f_PrintLog "Error" "Pls provide tool version, quit!"
        f_syntax
    fi
    tiup_tool=$(tiup list  | awk '{printf "%s ",$1}')
    tiup_mirror=$(tiup mirror show 2>/dev/null)

    for _tool in ${TiDBTools}
    do
        if [ $(echo "${tiup_tool}"|grep -w "${_tool}"|wc -l) -ge 1 ]
        then
            f_PrintLog "Info" "Install ${_tool} from tiup."
            f_PrintLog "Info" "tiup install ${_tool}:${clsversion}"
            tiup install ${_tool}:${clsversion}

            if [ $? -eq 0 -a -f ${TidbHome}/.tiup/components/${_tool}/${clsversion}/${_tool} ]
            then
                ls -l ${TidbHome}/.tiup/components/${_tool}/${clsversion}/${_tool}
                ls -l ${TidbHome}/.tiup/bin
                f_PrintLog "Info" "cp ${TidbHome}/.tiup/components/${_tool}/${clsversion}/*${_tool}* ${TidbHome}/.tiup/bin/"
                cp ${TidbHome}/.tiup/components/${_tool}/${clsversion}/*${_tool}* ${TidbHome}/.tiup/bin/
            else
                f_PrintLog "Error" "tiup install ${_tool} failed, pls check ~/.tiup/components and ~/.tiup/bin!!!"
            fi
        else
            f_PrintLog "Info" "Install ${_tool} from ${TIUP_MIRROR}"
            # f_PrintLog "Info" "wget $TIUP_WGET_REPO/${_tool}"
            # wget $TIUP_WGET_REPO/${_tool}
            ls -l ${TIUP_MIRROR} | grep ${_tool}
            _tool_tar1=$(ls -lt ${TIUP_MIRROR} | awk -v tl="${_tool}" '{if($NF==tl){printf "%s",$NF;exit}}')
            _tool_tar2=$(ls -lt ${TIUP_MIRROR} | grep "${_tool}.*tar.gz" | awk '{printf "%s",$NF;exit}')
            f_PrintLog "Debug" "_tool_tar1:${_tool_tar1} _tool_tar2:${_tool_tar2}"
            if [ -f ${TIUP_MIRROR}/${_tool_tar1:-123} ]
            then
                f_PrintLog "Info" "cp ${TIUP_MIRROR}/${_tool_tar1:-123} ${TidbHome}/.tiup/bin/"
                cp ${TIUP_MIRROR}/${_tool_tar1:-123} ${TidbHome}/.tiup/bin/
                local _rt_code=$?
            elif [ -f ${TIUP_MIRROR}/${_tool_tar2:-123} ]
            then
                f_PrintLog "Info" "tar -zxf ${TIUP_MIRROR}/${_tool_tar2:-123} -C ${TidbHome}/.tiup/bin/"
                tar -zxf ${TIUP_MIRROR}/${_tool_tar2:-123} -C ${TidbHome}/.tiup/bin/
                local _rt_code=$?
            else
                f_PrintLog "Error" "Tool ${_tool} not found in ${TIUP_MIRROR}, quit!!!"
            fi

                #statements
            if [ $_rt_code -eq 0 -a -f ${TidbHome}/.tiup/bin/${_tool} ]
            then
                ls -l ${TIUP_MIRROR} | grep ${_tool}
                ls -l ${TidbHome}/.tiup/bin
                # f_PrintLog "Info" "mv ${TIUP_MIRROR}/${_tool} ${TidbHome}/.tiup/bin"
                # mv ${TIUP_MIRROR}/${_tool} ${TidbHome}/.tiup/bin
            else
                f_PrintLog "Error" "Download ${_tool} failed, pls check!!!"
            fi
        fi
    done

}

###############################################################################
##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)
TiDBTools="sync_diff_inspector"
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;;
    -VERSION|-CLSVERSION) CurOpt="-VERSION";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -CLUSTER) declare clsname="${inopt}";continue;;
    -VERSION) declare clsversion="${inopt}";continue;;
    esac
done

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

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

function deploy_tools_main
{
    # HA role: primary or standby 

    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 
        if [ -z "${clsname}" -a -z "${clsversion}" ]
        then
            clsName=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
            clsversion=$(tiup cluster list 2>/dev/null|awk -v cn="${clsName}" '{if($1==cn){printf "%s\n",$3;exit}}') 
        elif [ -n "${clsname}" -a -z "${clsversion}" ]
        then
            clsName=$(tiup cluster list 2>/dev/null|awk -v cn="${clsName}" '{if($1==cn){printf "%s\n",$1;exit}}') 
            clsversion=$(tiup cluster list 2>/dev/null|awk -v cn="${clsName}" '{if($1==cn){printf "%s\n",$3;exit}}')
        fi
        
        f_disable_telemetry
        f_deploy_tools
    else
        f_PrintLog "Error" "Pls run script with user root or tidb, exit!!!"
    fi

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



deploy_tools_main

