#!/bin/bash

#set -x

. `dirname $0`/functions

THIS_SCRIPT_NAME="`basename $0`"

if [ $# -lt 1 ]; then
    write_switch_log "The $THIS_SCRIPT_NAME, the required parameters are missing."
    echo "error"
    exit 0
fi

REMOTE_HOST_NAME="$1"

reconfig_normal () {
    local script_name="$THIS_SCRIPT_NAME"
    local result=

    stop_backupd
    write_switch_log "The $script_name, Stop dbackup3-backupd service successfully."

    local stop_slave_sql="flush privileges; unlock tables; stop slave; reset slave all;"
    result=`local_db_execute_query "$stop_slave_sql" true`
    if [ $? -ne 0 ]; then
        write_switch_log "The $script_name, when reconfig_normal is called, \
statement '$stop_slave_sql' fails to execute on the local database server, result: $result."
        return 1
    fi

    write_switch_log "The $script_name, database reset slave successfully."

    local ip_address="`get_available_ip_address`"
    if [ -z "$ip_address" ]; then
        write_switch_log "The $script_name, there is no IP address in \
($PEER_HOST_ADDRESS_LIST) that can be successfully connected."
        return 1
    fi

    local binlog_sql="FLUSH TABLE WITH READ LOCK; SHOW MASTER STATUS; UNLOCK TABLES;"
    result=`peer_db_execute_query "$ip_address" "$binlog_sql" false`
    if [ $? -ne 0 ]; then
        write_switch_log "The $script_name, execution of SQL statement \
'$binlog_sql' on remote host $ip_address fails."
        return 1
    fi

    local file=`echo "$result" | grep -v File |awk '{print $1}'`
    local position=`echo "$result" | grep -v File |awk '{print $2}'`

    write_switch_log "The $script_name, the current database binlog file on \
the peer host($ip_address) is $file, and the position is $position."

    local change_master_cmd=`gen_change_replication_cmd "$ip_address" \
                                "$DB_PEER_PORT" "$file" "$position"`
    result=`local_db_execute_query "$change_master_cmd" true`
    if [ $? -ne 0 ]; then
        write_switch_log "The $script_name, the database service fails to \
switch to the slave node of peer host $ip_address, error: $result, sql: '$change_master_cmd'."
        return 1
    fi

    write_switch_log "The $script_name, the database service is \
successfully switched to the slave node of the peer host $ip_address."

    systemctl start dbackup3-keepalived
    return 0
}

write_switch_log "This $THIS_SCRIPT_NAME begins to be executed by ($REMOTE_HOST_NAME) request."
reconfig_normal
if [ $? -eq 0 ];then
    write_switch_log "This $THIS_SCRIPT_NAME was executed successfully by ($REMOTE_HOST_NAME)."
else
    write_switch_log "This $THIS_SCRIPT_NAME was executed failed by ($REMOTE_HOST_NAME)."
fi

echo "ok"
exit 0
