#!/bin/bash

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



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

function insertQueryOverride(){
  insertedTimestamp=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "INSERT INTO session(node, last_change, script_running) VALUES ('${host}', from_unixtime(${insertedTimestamp}), ${1}) returning unix_timestamp(last_change);")
}
function insertQuery(){
  insertedTimestamp=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "INSERT INTO session(node, script_running) VALUES ('${host}', ${1}) returning unix_timestamp(last_change);")
}

function selectTimestampQuery(){
  lastSelect=$(
    mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute \
    "SELECT unix_timestamp(last_change), script_running FROM session ORDER BY id DESC LIMIT 1;")

  lastTimestamp=$(echo ${lastSelect} | cut -d' ' -f1)
  script_running=$(echo ${lastSelect} | cut -d' ' -f2)
  currentTimestamp=$(mariadb --defaults-file=${confDir}/${confFile} \
    --skip-column-names \
    --silent \
    --execute "SELECT unix_timestamp();")
}

selectTimestampQuery

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

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

if [ ${script_running} -eq 0 ] && [ ${timeDifference} -ge 60 ]
then
  insertQuery true
  # insert script to be executed
  ${confDir}/gen_stats.sh $1
  insertQueryOverride false
else
  exit 0
fi
