#!/bin/env bash
#1_tiup_install.sh

#1.判断是否存在tidb用户
#2.切换到tidb用户,执行tiup下载和部署
#3.设置tiup mirror镜像地址

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    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_DownloadTiDBTar
{
    f_PrintLog "Debug" "Start to run Script f_DownloadTiDBTar"
    _file=$1
    if [ -f ${_file} ]
    then
        f_PrintLog "Info" "File ${_file} already exist, not need wget."
        ls -l  ${_file}
    else
        f_PrintLog "Info" "wget ${TIUP_WGET_REPO}/${_file} --timeout=30 --tries=3"
        wget ${TIUP_WGET_REPO}/${_file} --timeout=30 --tries=3
        if [ $? -eq 0 -a -f ${_file} ] 
        then
            f_PrintLog "Succ" "Download ${_file} successfully."
            ls -l ${_file}
        else
            f_PrintLog "Error" "Download ${_file} failed!!!"
            rm -f ${_file}
            exit 1
        fi
    fi
}

function f_CheckTiup
{
    f_PrintLog "Debug" "Start to run Script f_CheckTiup"
    f_PrintLog "Info" "which tiup: $(which tiup)"
    f_PrintLog "Info" "tiup mirror show: $(tiup mirror show)"
    tiup --version 
    _rt_code=$?
    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Info"  "Tiup install successful."
    else
        f_PrintLog "Error"  "Tiup install failed."
        exit 1
    fi
}

function f_InstallTiup
{
    f_PrintLog "Debug" "Start to run Script f_InstallTiup"
    if [ -f ${TidbHome}/.tiup/bin/tiup ]
    then
        ls -l  "${TidbHome}/.tiup/bin"
        f_PrintLog "Warn" "Binary file already exist in ${TidbHome}/.tiup/bin, quit!!!"
        return 0
    fi

    f_DownloadTiDBTar "${TIDB_SERVER_FILE}"
    f_PrintLog "Info" "tar zxf ${TIDB_SERVER_FILE} -C ${TIUP_MIRROR}"
    tar zxf ${TIDB_SERVER_FILE} -C ${TIUP_MIRROR}
    f_PrintLog "Info" "sh ${TIUP_MIRROR}/${TIDB_SERVER_FILE%.tar.gz}/local_install.sh"
    sh ${TIUP_MIRROR}/${TIDB_SERVER_FILE%.tar.gz}/local_install.sh
    source  ${TidbHome}/.bash_profile

    f_PrintLog "Info" "tiup mirror show after update..."
    ${TidbHome}/.tiup/bin/tiup mirror show  
    f_CheckTiup


    # f_DownloadTiDBTar "${TIDB_TOOLKIT_FILE}"

    f_PrintLog "Info" "tiup mirror show after update..."
    ${_bindir}/tiup mirror show 2>/dev/null

    f_DownloadTiDBTar "${TIDB_TOOLKIT_FILE}"
    f_PrintLog "Info" "tar zxf ${TIDB_TOOLKIT_FILE} -C ${TIUP_MIRROR}"
    tar zxf ${TIDB_TOOLKIT_FILE} -C ${TIUP_MIRROR}
    cp -rp ${TIUP_MIRROR}/${TIDB_SERVER_FILE%.tar.gz}/keys ${TidbHome}/.tiup/
    f_PrintLog "Info" "tiup mirror merge ${TIUP_MIRROR}/${TIDB_TOOLKIT_FILE%.tar.gz}"
    tiup mirror merge ${TIUP_MIRROR}/${TIDB_TOOLKIT_FILE%.tar.gz}
    _rt_code=$?
    if [ ${_rt_code} -eq 0 ]
    then
        f_PrintLog "Succ" "tiup mirror merge ${TIDB_TOOLKIT_FILE%.tar.gz} successfully."
    else
        f_PrintLog "Error" "tiup mirror merge ${TIDB_TOOLKIT_FILE%.tar.gz} failed, return:${_rt_code}"
    fi

    f_CheckTiup
}


###############################################################################
##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##
case $(uname -m) in
    amd64|x86_64) arch=amd64 ;;
    arm64|aarch64) arch=arm64 ;;
    *) arch= ;;
esac

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

TIDB_SERVER_FILE="tidb-community-server-v6.1.1-linux-${arch}.tar.gz"
TIDB_TOOLKIT_FILE="tidb-community-toolkit-v6.1.1-linux-${arch}.tar.gz"
TIUP_MIRROR=""

TidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
TIUP_HOME="${TidbHome}/.tiup"
###############################################################################
###############################################################################
####Main####

function tiup_main
{
    if [ ${UserID} -eq 0 ]
    then
        # f_CheckUser tidb
        user_grp=$(groups tidb|awk -F: '{gsub(" ","",$2);{printf $2}}')
        mkdir -p  /tidbmgt/package
        chown tidb.${user_grp:-tidb}  /tidbmgt/package

        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
        mkdir -p ${TidbHome}/scripts
        
        tiup --version 
        if [ $? -eq 0 ]
        then
            f_PrintLog "Warn" "Tiup already installed on host, quit!"
            f_CheckTiup
            exit 0
        fi

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

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


tiup_main
