#!/bin/bash

restartFlagFile=$1
restartLogFile=$2

SVC(){ systemctl --help &>/dev/null && systemctl $2 $1 || (service --help &>/dev/null && service $1 $2); }

if ! SVC zabbix-agent status &>/dev/null || grep -q ToBeRestarted $restartFlagFile
then
  exec &> $restartLogFile
  echo "`date`: [INFO] Either ZabbixAgent is not in 'RUNNING' state or RestartFlag is set to 'ToBeRestarted', attempting to restart Zabbix Agent:"
  for ((counter=1;counter <= 3;counter++))
  do
    echo `date`: [INFO] Try "#$counter"...
        SVC zabbix-agent restart
        SVC zabbix-agent status && echo SUCCESS! && echo `date`: [INFO] Zabbix Agent started successfully, resetting RestartFlag.  && echo Restarted At: `date` > $restartFlagFile && exit
        echo FAIL. Sleeping for 10s.
        sleep 10
  done
  echo `date`: [ERROR] Try '#3' failed, removing all files from '/etc/zabbix/zabbix_agentd.d' and starting the agent.  && rm -vf /etc/zabbix/zabbix_agentd.d/* && SVC zabbix-agent start; SVC zabbix-agent status
fi

date -u
SVC zabbix-agent status