#!/bin/bash

host=$(hostname)$1
currentTimestamp=""
lastTimestamp=""
confDir=/opt/cron_script
confFile=".my.cnf"
checkInterval=20

currentMaster=""

if [ "$(ps -ef | grep -v grep | grep $0 | grep -v $$)" ]
then
  logger "kill $0: $$"
  exit 0
fi

function selectCurrentTimestamp(){
  currentTimestamp=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "SELECT unix_timestamp();")
}

function selectTimestamp(){
  lastTimestamp=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "SELECT last_change FROM master ORDER BY id DESC LIMIT 1;")
}

function selectMasterState(){
  currentMaster=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "SELECT master FROM master ORDER BY id DESC LIMIT 1;")
}

function insertQuery(){
  mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "INSERT INTO master(master) VALUES ('${host}');"
}



selectMasterState
selectTimestamp
selectCurrentTimestamp

timeDifference=$(expr ${currentTimestamp} - ${lastTimestamp})

if [ ${timeDifference} -ge ${checkInterval} ]
then
	insertQuery 
	exit 0
fi

if [ "${currentMaster}" = "${host}" ]; then
  ${confDir}/minute_check.sh $1
  insertQuery
fi
