#!/bin/bash
# checking if http is really down 
if systemctl is-active --quiet httpd.service ; then 
  echo "Http seems to be in active state, kindly check server side if alert is not closed"; 
  exit
fi

#Getting apache down time stamp from  systemctl
check_apache_down_time_stamp=$(systemctl show httpd --property=ActiveExitTimestamp | awk -F"="  '{print substr($2, 1, length($2)-3)}'  | cut -d: -f1,2)
#echo "printing last apache down time ""$check_apache_down_time_stamp"""

#Converting timestamp to epoch time
con_time_epoch=$(date -d "$check_apache_down_time_stamp" +"%s")
#echo "Successfully converted to epoch time "$con_time_epoch"""

#Sometimes apache down time is few seconds ahead compare to bad user entry in log, so adjusting the same
adjusted_apache_downtime=$(( con_time_epoch - 120 ))

#Again coverting epoch to regular time stamp as per to match apache logs time stamp
con_epoch_to_regular=$(date +"%a %b %d %H:%M:%S %Y" -d@"$adjusted_apache_downtime" |cut -d: -f1,2)
#echo "coverted time stamp as per apache logs ""$con_epoch_to_regular"""

#Getting current system time for case condition
current_system_time=$(date  '+%a %b %_d %H:%M')

/usr/bin/logger -t $0 "Bad user http restart auto-remediation started"

# Regex to search bad user in logs between current and apache down time stamps
if sed -n "\#\[""$con_epoch_to_regular""#, \#\[""$current_system_time""#p" /var/log/apache2/error_log | grep "httpd: bad" ; then
  /root/bin/montool clearsemaphores 
  /scripts/restartsrv_httpd
else
  echo "apache went down not due to a bad user, Please investigate further. By any chance if its still due to a bad user, please report to SD"	
fi
