#!/bin/bash

#set -x

. `dirname $0`/functions

THIS_SCRIPT_NAME="`basename $0`"

write_switch_log "The $THIS_SCRIPT_NAME-----[$*]"

CHECK_INTERVAL=${CHECK_INTERVAL:=1}
MAX_CHECK_TIMES=${MAX_CHECK_TIMES:=30}

COUNT=1
while true
do
    if pgrep $DB_BACKGROUND_PROCESS_NAME > /dev/null; then
        result=`local_db_execute_query "show status;" true`
        if [ $? -ne 0 ]; then
            write_switch_log "The $THIS_SCRIPT_NAME, the database($DB_LOCAL_ADDRESS)\
 is running, but the SQL command 'show status;' fails($result)."
        fi

        exit 0
    fi

    write_switch_log "The $THIS_SCRIPT_NAME, The $COUNT time the database service was detected to be down."

    if [ $COUNT -gt $MAX_CHECK_TIMES ]; then
        systemctl stop dbackup3-backupd
        systemctl stop dbackup3-keepalived
        write_switch_log "The $THIS_SCRIPT_NAME, The database service($DB_LOCAL_ADDRESS) is down, and a switch is performed."
        break
    fi

    COUNT=$((COUNT + 1))
    sleep $CHECK_INTERVAL
done
