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

#1.更新系统参数


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_set_var
{
    f_PrintLog "Debug" "Start to run function f_set_var"
    _connstr=$1
    i_s=0
    i_f=0
    echo "${VAR1}" >/tmp/tidb_set.sql
    while read _var
    do
        _var_name=$(echo ${_var} | awk -F= '{gsub(" ","",$1);print $1}')
        _var_value=$(echo ${_var} | awk -F= '{gsub("^ *","",$2);print $2}')

        _val0=$(mysql ${_connstr} -NBe "select @@${_var_name}" | tr a-z A-Z)
        f_PrintLog "Info" "tidb variable ${_var_name} = ${_val0} before update..."

        f_PrintLog "Info" "mysql ${_connstr} -e set global ${_var_name} = ${_var_value}"
        mysql ${_connstr} -e "set global ${_var_name}=${_var_value}"
        _rt_code=$?

        _val0=$(mysql ${_connstr} -NBe "select @@${_var_name}" | tr a-z A-Z)
        f_PrintLog "Info" "tidb variable ${_var_name} = ${_val0} after update..."

        _val1=$(mysql ${_connstr} -NBe "select @@${_var_name}" | tr a-z A-Z)
        _var2=$(echo ${_var_value}|sed "s/'//g" |tr a-z A-Z)

        if [ ${_rt_code} -eq 0 -a "${_val1}" = "${_var2}" ]
        then
            f_PrintLog "Succ" "update variable ${_var_name} = ${_var_value} successfully."
            i_s=$((i_s+1))
        elif [ ${_rt_code} -eq 0 -a "${_val1}" = "1" -a "${_var2}" = "NO" ]
        then
            f_PrintLog "Succ" "update variable ${_var_name} = ${_var_value} successfully."
            i_s=$((i_s+1))
        elif [ ${_rt_code} -eq 0 -a "${_val1}" = "0" -a "${_var2}" = "OFF" ]
        then
            f_PrintLog "Succ" "update variable ${_var_name} = ${_var_value} successfully."
            i_s=$((i_s+1))
        else
            f_PrintLog "Warn" "update variable ${_var_name} failed, return: ${_rt_code} ${_val1} ${_val2}!!!"
            i_f=$((i_f+1))
        fi
    done </tmp/tidb_set.sql

    if [ ${i_f} -ge 1 ]
    then
        f_PrintLog "Error" "update variable failed, succ count:${i_s}, fail count:${i_f}!!!"
        exit 1
    else
        f_PrintLog "Info" "update variable successfully, succ count:${i_s}, fail count:${i_f}!!!"
    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##
TIUP_LOGINPATH=""
TidbHome=$(awk -F: -v un="tidb" '{if($1==un){print $6;exit}}' /etc/passwd 2>/dev/null)
VAR1="tidb_auto_analyze_start_time = '22:00 +0800'
tidb_auto_analyze_end_time = '04:00 +0800'
transaction_isolation = 'READ-COMMITTED'
tidb_gc_life_time = '12h0m0s'
tidb_analyze_version = 2
tidb_enable_clustered_index = off
tidb_skip_isolation_level_check = 0
tidb_auto_analyze_ratio = 0.1
tidb_stmt_summary_max_stmt_count = 10000
tidb_enable_noop_functions = off
tidb_enable_outer_join_reorder = off
tidb_enable_top_sql = off
tidb_mem_oom_action = cancel
tidb_mem_quota_analyze = 10737418240
tidb_mem_quota_query = 10737418240
tidb_memory_usage_alarm_ratio = 0.5
tidb_query_log_max_len = 4194304
tidb_slow_log_threshold = 300"

###############################################################################
###############################################################################
##Get inopt
# [ -z "${ShellOption}" ] && f_syntax;
for inopt in ${ShellOption}
do
    case $(echo $inopt|tr a-z A-Z) in
    -IP) CurOpt="-IP";continue;;
    -PORT) CurOpt="-PORT";continue;;
    -USER) CurOpt="-USER";continue;;
    -PASSWORD|-PSWD) CurOpt="-PSWD";continue;;
    -HELP|--HELP|-H) f_syntax;;
    -*) CurOpt="";continue;;
    esac
    case "${CurOpt}" in
    -IP) declare ip="${inopt}";continue;;
    -PORT) declare port="${inopt}";continue;;
    -USER) declare user="${inopt}";continue;;
    -PSWD) declare pswd="${inopt}";continue;;
    esac
done

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

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


function set_var_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
        if [ -n "${ip}" -a -n "${port}" ]
        then
            tidb_connstr="-h${ip} -P${port} -u${user:-root} -p${pswd:-123}"
        else
            tidb_connstr="--login-path="
        fi

        f_set_var "${tidb_connstr}"
    else
        f_PrintLog "Error" "Pls run script with user root or tidb, exit!!!"
    fi

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

set_var_main

