#!/bin/bash

KEEPALIVED_CONFIG_FILE="/tmp/keepalived.conf"
CHECK_STATUS_SCRIPT_FILE="/tmp/chk_slave.sh"
KEEPALIVED_NOTIFY_SCRIPT_FILE="/tmp/notify.sh"

help_str="
This scripts is used to config MySQL multi master.

Parameter Description:
  -h:           Print help infomation.
  -k:           Parse path of keepalived rpm package.
  -c:           Choose whether to initialize the MySQL multi configuration file.
"

exec_on_container() {
    container_id=$(docker ps |grep mysql:v8 |awk '{print $1}')
    exec_sql="mysql -urepl -pXjb0^DDy -e"

    if [ "$1" == "sql" ];then
        docker exec  $container_id $exec_sql "$2"
    else
        docker exec  $container_id bash -c "$*"
    fi
}

gen_conf() {
cat >${KEEPALIVED_CONFIG_FILE}<<EOF
! Configuration File for keepalived
global_defs {
    router_id EDOC_HA
}
vrrp_script chk_slave {
    script "/etc/keepalived/chk_slave.sh"
    interval 3
    weight -3
}

vrrp_instance VI_1 {
    interface _INTFS
    state _ROLE
    priority _PRIORITY
    nopreempt
    virtual_router_id 81
    garp_master_delay 1
    authentication {
        auth_type PASS
        auth_pass password
    }
    track_interface {
        _INTFS
    }
    virtual_ipaddress {
        _VIP/32
    }

    track_script {
        chk_slave
    }
    notify_master "/etc/keepalived/notify.sh master"
    notify_backup "/etc/keepalived/notify.sh backup"
    notify_fault "/etc/keepalived/notify.sh fault"
}
EOF


cat >${CHECK_STATUS_SCRIPT_FILE}<<'EOF'
#!/bin/bash

exec_sql() {
    container_id=$(docker ps |grep mysql:v8 |awk '{print $1}')
    conn_db="mysql -urepl -pXjb0^DDy -N -e"
    docker exec  $container_id $conn_db "$1"
}

# io_running=$(exec_sql "show slave status \G" |grep SQL_Running: | awk '{print $2}')
# sql_running=$(exec_sql "show slave status \G" |grep SQL_Running: | awk '{print $2}')
# seconds_behind=$(exec_sql "show slave status \G" |grep Seconds_Behind_Master: | awk '{print $2}')

# if [ ${io_running} == "Yes" -a ${sql_running} == "Yes" -a ${seconds_behind} -lt 10 ]; then
#     exit 0
# else
#     exit 1
# fi

exec_sql "select 1"
if [ $? -eq 0 ]; then
    exit 0
else
    /usr/bin/systemctl stop keepalived
    exit 1
fi

EOF

cat >${KEEPALIVED_NOTIFY_SCRIPT_FILE}<<'EOF'
#!/bin/bash

exec_sql() {
    container_id=$(docker ps |grep mysql:v8 |awk '{print $1}')
    conn_db="mysql -urepl -pXjb0^DDy -e"
    docker exec  $container_id $conn_db "$1"
}

case $1 in
    master)
        exec_sql "set global read_only=off"
        ;;
    backup)
        exec_sql "set global super_read_only=on"
        ;;
    fault)
        exec_sql "set global super_read_only=on"
        ;;
esac

EOF

}


install() {
    [ -f ${KEEPALIVED_CONFIG_FILE} ] && >${KEEPALIVED_CONFIG_FILE}
    [ -f ${CHECK_STATUS_SCRIPT_FILE} ] && >${CHECK_STATUS_SCRIPT_FILE}
    [ -f ${KEEPALIVED_NOTIFY_SCRIPT_FILE} ] && >${KEEPALIVED_NOTIFY_SCRIPT_FILE}
    gen_conf

    _intfs=($(ip -4 a | awk -F: '$2 !~ /lo|docker/{print $2}' | xargs))
    if [ ${#_intfs[@]} -gt 1 ];then 
        echo "Your localhost got many network inteface, please select one of them used for listen VRRP."
        for ((i=0; i<${#_intfs[@]}; i++));  do
            echo -e "[$(($i+1))]: ${_intfs[$i]}"
        done
        read _NUM
        _IDX=_NUM-1
        _INTFS=${_intfs[$_IDX]}
    elif [ ${#_intfs[@]} -eq 0 ]; then
        echo "Could not get any interface in you host."
        exit 104 
    else
        echo -e "You got one network interface: ${_intfs[@]}. This interface will be used for listen VRRP"
        _INTFS=${_intfs[@]}
    fi
    echo "Plase input your virtual ip address without netmask."
    read _VIP
    echo $_VIP | awk -F. '{if(NF==4 && $1>0 && $1<=255 && $2>=0 && $2<=255 && $3>=0 && $3<=255 && $4>0 && $4<255) exit 0;else exit 1}'
    if [ $? -ne 0 ]; then
        echo "Invalid IP address founded. Please check your input."
        exit 102
    fi
    echo -e "Please input role of this node.\n[1] master \n[2] backup"
    read _CHOSE
    _ROLE=BACKUP
    if [ ${_CHOSE} -eq 1 ]; then 
        _PRIORITY=100
    else 
        _PRIORITY=98
    fi
    # echo "Please input priority of this node, 0 ~ 100"
    # read _PRIORITY

    eval sed -i 's/_INTFS/${_INTFS}/g' ${KEEPALIVED_CONFIG_FILE}
    eval sed -i 's/_VIP/${_VIP}/g' ${KEEPALIVED_CONFIG_FILE}
    eval sed -i 's/_PRIORITY/${_PRIORITY}/g' ${KEEPALIVED_CONFIG_FILE}
    eval sed -i 's/_ROLE/${_ROLE}/g' ${KEEPALIVED_CONFIG_FILE}

    echo "Got ya. Now process keepalived install."
    [ ! -f ${keepalived_pkg} ] && echo "Keepalived package not found."
    rpm -ivh ${keepalived_pkg}
    if [ $? -eq 0 ]; then
        /usr/bin/cp -f ${KEEPALIVED_CONFIG_FILE} /etc/keepalived/keepalived.conf
        /usr/bin/cp -f ${CHECK_STATUS_SCRIPT_FILE} /etc/keepalived/chk_slave.sh && chmod +x /etc/keepalived/chk_slave.sh
        /usr/bin/cp -f ${KEEPALIVED_NOTIFY_SCRIPT_FILE} /etc/keepalived/notify.sh && chmod +x /etc/keepalived/notify.sh
        echo "Keepalived install successed. Now start keepalived."
    else 
        echo "Keepalived install failed."
        exit 103
    fi

    systemctl enable --now keepalived
    if [ $? -eq 0 ]; then 
        rm -fr ${KEEPALIVED_CONFIG_FILE}
        rm -fr ${CHECK_STATUS_SCRIPT_FILE}
    fi
}

# 当前v8.0.17.15版本双主默认没有配置自增步长，后续增加默认配置可以删除此配置
# 此修改为临时修改，重启后会失效，如需永久修改，需要挂载配置文件修改


main() {
    declare -a names

    getopt_cmd=$(getopt -o k:h -n $(basename $0) -- "$@")
    [ $? -ne 0 ] && exit 1
    eval set -- "$getopt_cmd"
    # 解析选项
    while [ -n "$1" ]
    do
        case "$1" in
            -k)
                keepalived_pkg="$2"
                install
                shift ;;
            -h)
                echo -e "$help_str"
                exit ;;
            --)
                shift
                break
            ;;
            *)
                echo -e "$help_str"
                # log error "Parameter error!"
                exit 1 ;;
        esac
        shift
    done

    # while [ -n "$1" ]
    # do
    #     names=("${names[@]}" "$1")
    #     shift
    # done
}


main $@
