#!/bin/env bash
##Description: run sqlfile or sql stmt

function f_syntax
{
    [ ! -z "$1" ] && echo ">>[$(date "+%Y%m%d.%H%M%S")] $1"
    echo " "
    echo "ksh ${ShellName}  [-clsname <clsname>] [-hostname <hostname>]"
    echo "  [-ip <ip>] [-port <port>] [-user <user>] [-passwd <passwd>]  "
    echo "  [-stmt <select ...>] "
    echo "  [-sqlfile <select.txt>] "
    echo "  [-run -check]"
    echo " "
    echo " #sample:"
    echo " #sh ${ShellName} -IP 172.16.xxx -port 4000 -user abcuser1 -passwd xxx -filetype sql -backupdir /home/tidb/ccb_scripts/dr_switchover/tmp -backupsizemb 100 "
    echo " #sh ${ShellName} -IP 172.16.xxx -port 4100 -user abcuser1 -passwd xxx -filetype sql -backupdir /data2/tmp -backupsizemb 100 "
    exit 22
}

function f_PrintLog
{
    _LogFlag=$(echo "$1"|tr "a-z" "A-Z")
    [ $(echo "$1"|wc -L) -eq 4 ] && _LogFlag=$(echo "${_LogFlag}_")
    _LogMessage=$2
    declare LogFile="${LogFile:-"/tmp/${PShellName:-${ShellName}}.log"}"
    touch "${LogFile}" 2>/dev/null
    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
}


###############################################################################
##Init##
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
LogFile="${LogDir}/${ShellName}.$(date "+%Y%m%d.%H%M%S").log";LogLevel=3;
touch "${LogFile}" 2>/dev/null;chmod ugo+rw "${LogFile}" 2>/dev/null
declare Shellcksum=$(cksum ${WorkDir%/}/${ShellName} 2>/dev/null|awk '{printf "%d",$1}')
declare -i UserID=$(id -u);declare UserName=$(whoami);declare HostName=$(hostname);
###############################################################################
##Get inopt
[ -z "${ShellOption}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -HOSTNAME|-HOST) CurOpt="-HOSTNAME";continue;;
    -IP) CurOpt="-IP";continue;;
    -PORT) CurOpt="-PORT";continue;;
    -USER|-U) CurOpt="-USER";continue;;
    -PASSWORD|-PASSWD) CurOpt="-PASSWORD";continue;;
    -FILETYPE|-T) CurOpt="-FILETYPE";continue;;
    -BACKUPDIR|-B) CurOpt="-BACKUPDIR";continue;;
    -BACKUPSIZEMB|-D) CurOpt="-BACKUPSIZEMB";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -HOSTNAME) declare LocalHost="${inopt}";continue;;
    -IP) declare tidbip="${inopt}";continue;;
    -PORT) declare tidbport="${inopt}";continue;;
    -USER) declare tidbuser="${inopt}";continue;;
    -PASSWORD) declare tidbpasswd="${inopt}";continue;;
    -FILETYPE) declare filetype="${inopt}";continue;;
    -BACKUPDIR) declare backupdir="${inopt}";continue;;
    -BACKUPSIZEMB) declare baksizemb="${inopt}";continue;;
    esac
done

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

function f_rundumpling
{
    f_PrintLog "Info" "Start to run f_rundumpling."
    _sqlfile=$1
    _dt=$(date "+%Y%m%d.%H%M%S")
    _snapshot=$(date "+%Y-%m-%d %H:%M:%S")

    _backupdir=${backupdir}/${_dt}
    _logdir=${backupdir}/logs

    _logfile=${backupdir}/logs/dumpling_${_dt}.log
    mkdir -p ${_backupdir}
    mkdir -p ${_logdir}
    
    tiup dumpling -V
    f_PrintLog "Info" "start to run tiupdumpling, log file:${_logfile} "
    f_PrintLog "Info" "parameter: -h ${tidbip} -P ${tidbport} -u ${tidbuser} -o ${_backupdir} --filetype ${filetype} --params ${enginetype} -t ${thread} -r 200000 -F 256MiB"

    tiup dumpling \
        -u ${tidbuser} \
        -P ${tidbport} \
        -p ${tidbpasswd} \
        -h ${tidbip} \
        -o ${_backupdir} \
        --filetype ${filetype} \
        --params ${enginetype} \
        -t ${thread} \
        -r 200000 \
        -F 256MiB   >> ${_logfile} 2>&1

    _rt_code=$?
    f_PrintLog "Info" "run tiup dumpling finished, retrun ${_rt_code}, backup dir is ${_backupdir} "
    return ${_rt_code}
}

function f_checkspace
{
    df -h
    diskfree=$(df -P -m ${backupdir}|awk '!/Filesystem/{printf "%d",$3;exit}')
    if [ $diskfree -gt ${baksizemb:-1} ]
    then
        f_PrintLog "Info" "backup dir ${backupdir} free space is ${diskfree}MB, greater then ${baksizemb}MB"
    else
        f_PrintLog "Error" "backup dir ${backupdir} free space is ${diskfree}MB, less then ${baksizemb}MB, quit!!!"
        exit 1
    fi
}


function f_delbakhis
{
    ls -l 
    #确认删除策略
}

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

#dumpling config
enginetype='tidb_isolation_read_engines=tikv'
thread=8

#
if [ -z "${backupdir}" ]
then 
    f_PrintLog "Error" "Pls provide backupdir parameter by -backupdir option!!!"
    f_syntax
fi

f_checkspace
f_rundumpling 

