#!/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"
    mysql -urepl -p'Xjb0^DDy' -e "$1"
}


io_running=$(exec_sql "show slave status \G" 2>/dev/null | grep Slave_IO_Running: | awk '{print $2}')
sql_running=$(exec_sql "show slave status \G" 2>/dev/null | grep Slave_SQL_Running: | awk '{print $2}')
seconds_behind=$(exec_sql "show slave status \G" 2>/dev/null | grep Seconds_Behind_Master: | awk '{print $2}')

if [ ${io_running} == "Yes" -a ${sql_running} == "Yes" -a ${seconds_behind} -lt 60 ]; then
    [[ !  $(ps -ef|grep keepalived |grep -v grep ) ]] && /usr/bin/systemctl start keepalived 
    exit 0
else
    # Send mail
    # There was a problem with syncing:
    # io_running: ${io_running}
    # sql_running: ${sql_running}
    # seconds_behind: ${seconds_behind}

    echo "[$(date "+%F %H:%M:%S")] Slave status fault." >> /tmp/check_slave.log
    exit 1
fi
