#!/bin/env bash
#10_tidb_deploy_scripts.sh


function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "Syntax:"
    echo "bash ${ShellName} "
    echo "-backuptime <20:00> "
    echo " "
    echo " #Description:"
    echo " -backuptime ,the tidb backup time"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -backuptime 20:00 " 
    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_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_analyze
{
    f_PrintLog "Debug" "Start to run function f_analyze"
    # f_analyze "${TidbHome}/scripts/analyze"  gather_alltab_stats.py
    local _dir=$1
    local _script=$2
    f_wget ${_dir} ${_script}
    # python gather_alltab_stats.py
}

function f_arsenal
{
    f_PrintLog "Debug" "Start to run function f_arsenal"
    # f_arsenal "${TidbHome}/scripts/arsenal"  .zip
    local _dir=$1
    local _script=$2
    f_wget ${_dir} ${_script}
    cd ${_dir}
    unzip -o ${_script}
    cd ${WorkDir}
}

function f_check_usage
{
    f_PrintLog "Debug" "Start to run function f_check_usage"
    # f_check_usage "${TidbHome}/scripts/check_usage"  .py
    local _dir=$1
    local _script=$2
    f_wget ${_dir} ${_script}
}

function f_dailycheck
{
    f_PrintLog "Debug" "Start to run function f_dailycheck"
    # f_dailycheck "${TidbHome}/scripts/dailycheck" 
    local _dir=$1
    f_wget ${_dir} xfile.sh
    f_wget ${_dir} zfile.out
    local tidb_grp=$(groups tidb|awk -F: '{gsub(" ","",$2);{printf $2}}')
    chown tidb.${_u_grp} ${_dir}

    cd ${_dir}
    sh xfile.sh  zfile.out
    sh install.sh
    cd ${WorkDir}

    su - tidb -c "sh ${_dir}/run_dailycheck_tidb.sh"
    
}

function f_switchover
{
    f_PrintLog "Debug" "Start to run function f_switchover"
    # f_switchover "${TidbHome}/scripts/switchover"  .tar.gz
    local _dir=$1
    local _script=$2
    f_wget ${_dir} ${_script}
    cd ${_dir}
    tar -zxf ${_script}  
    cd ${WorkDir}
}

function f_tidb_check
{
    f_PrintLog "Debug" "Start to run function f_tidb_check"
    # f_tidb_check "${TidbHome}/scripts/tidb_check"  .sh
    local _dir=$1
    local _script=$2
    f_wget ${_dir} ${_script}
    # sh tidb_nonfunction.sh
}

function f_tidb_guard
{
    f_PrintLog "Debug" "Start to run function f_tidb_guard"
    # f_tidb_guard "${TidbHome}/scripts/tidb_guard" 
    local _dir=$1
    f_wget ${_dir} tidb_status.py
    f_wget ${_dir} tidb_guard.sh
    tiup cluster exec ${cluster_name} -R tidb --command "mkdir -p ${TidbHome}/scripts/tidb_guard/logs"
    tiup cluster push ${cluster_name} -R tidb ${_dir}/tidb_guard.sh ${_dir}/tidb_guard.sh 
    tiup cluster push ${cluster_name} -R tidb ${_dir}/tidb_status.py ${_dir}/tidb_status.py 
    tiup cluster exec ${cluster_name} -R tidb --command "chmod a+x ${_dir}/tidb_guard.sh"
    tiup cluster exec ${cluster_name} -R tidb --command "chmod a+x ${_dir}/tidb_status.py "
    
    local _cron_exist=$(crontab -l | grep "tidb_guard" |wc -l)
    if [ ${_cron_exist} -eq 0 ]
    then
        tiup cluster exec ${cluster_name} -R tidb --command "crontab -l > /tmp/conf 2>&1 && grep -v 'no crontab' /tmp/conf >/tmp/conf1 ;echo '*/1 * * * * sh /home/db/tidb/scripts/tidb_guard/tidb_guard.sh >>/home/db/tidb/scripts/tidb_guard/logs/tidb_guard.log 2>&1'>> /tmp/conf1 && crontab /tmp/conf1 "
    fi
}

function f_backup
{
    f_PrintLog "Debug" "Start to run function f_backup"
    # f_backup "${TidbHome}/scripts/backup"   
    local _dir=$1
    mkdir -p ${_dir}/dumpling/logs
    mkdir -p ${_dir}/binlog/logs

    f_wget "${_dir}/dumpling" backup_dumpling_to_cos.sh
    f_wget "${_dir}/binlog" binlog_to_cos.sh
}


function f_crontab_write
{
    f_PrintLog "Debug" "Start to run function f_crontab_write"
    local _cron=$1

    _cron_script=$(echo "${_cron}" | awk '{printf "%s",$7}')
    _cron_exist=$(crontab -l | awk -v sc="${_cron_script}" '{if($7==sc){print $7;exit}}')

    if [ "${_cron_script}" = "${_cron_exist}" ]
    then
        f_PrintLog "Warn" "Crontab command already exist, skip."
        f_PrintLog "Warn" "${_cron}"
    else
        touch /tmp/tidb_cron
        crontab -l > /tmp/tidb_cron
        echo "${_cron}" >> /tmp/tidb_cron
        crontab /tmp/tidb_cron
        crontab -l
        f_PrintLog "Info" "Crontab command deploy finish."
    fi
}


function f_crontab_file
{
    f_PrintLog "Debug" "Start to run function f_crontab_file"
    local _u=$1
    if [ ! -f "/var/spool/cron/${_u}" ]
    then
        f_PrintLog "Info" "Generate crontab file start..."
        ls -l /var/spool/cron/
        touch /var/spool/cron/${_u}
        chmod 600 /var/spool/cron/${_u}
        if [ "${_u}" != "${UserName}" ]
        then
            local _u_grp=$(groups ${_u}|awk -F: '{gsub(" ","",$2);{printf $2}}')
            chown ${_u}.${_u_grp} /var/spool/cron/${_u}
        fi

        f_PrintLog "Info" "Generate crontab file finish..."
        ls -l /var/spool/cron/
    else
        f_PrintLog "Info" "Crontab file already exist..."
        ls -l /var/spool/cron/
        cat /var/spool/cron/${_u}
    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)
TIUP_HOME="${TidbHome}/.tiup"

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;;
    -BACKUPTIME) CurOpt="-BACKUPTIME";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -SLAVEIP) declare slaveip="${inopt}";continue;;
    -BACKUPTIME) declare backuptime="${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_crontab_main
{
    f_PrintLog "Debug" "Start to run function deploy_crontab_main"
    if [ "${UserName}" = "tidb" ]
    then
        crontab -l

        local _hr=$(echo "${backuptime}"|awk -F: '{printf "%s",$1}')
        local _tm=$(echo "${backuptime}"|awk -F: '{printf "%s",$2}')
    
        if [ "${harole}" = "PRIMARY" ]
        then
        else
        fi
        crontab -l
    fi
    f_PrintLog "Succ" "Run function deploy_crontab_main finish!"

}


function deploy_scripts_main
{
    # HA role: primary or standby 

    if [ ${UserID} -eq 0 ]
    then
        f_dailycheck "${TidbHome}/scripts/dailycheck" 

        # 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
        cluster_name=$(tiup cluster list 2>/dev/null|awk '{if($3~"v" && $4~"tiup"){printf "%s\n",$1;exit}}') 
        if [ -n "${cluster_name}" ]
        then
            tiup cluster display ${cluster_name}
        else
            f_PrintLog "Error"  "Cluster ${cluster_name} not exist, quit!"
            tiup cluster list
            exit 1
        fi

        f_analyze "${TidbHome}/scripts/analyze"  .py
        f_arsenal "${TidbHome}/scripts/arsenal"  .zip
        f_check_usage "${TidbHome}/scripts/check_usage"  .py
        f_switchover "${TidbHome}/scripts/switchover"  .tar.gz
        f_tidb_check "${TidbHome}/scripts/tidb_check"  .sh
        f_tidb_guard "${TidbHome}/scripts/tidb_guard" 
        f_backup "${TidbHome}/scripts/backup" 

        deploy_crontab_main
    fi
    f_PrintLog "Succ" "Run function deploy_scripts_main finish!"
}





deploy_scripts_main
deploy_crontab_main

