#!/bin/bash

max_cpu_threshold=90

process_name=$1
logger -s "$process_name is found as argument"

if [[ $process_name == "squid" ]];then
        logger -s "inside squid IF"
        cpu[0]=`/usr/bin/top -cbn1 | grep -iw "/opt/squid/sbin/squid" | grep -v grep | /bin/awk '{ print $9 }'`
        cpu[1]=`/usr/bin/top -cbn1 | grep -iw "(squid-1)" | grep -v grep | /bin/awk '{ print $9 }'`
else
        logger -s "inside ss5 IF"
        cpu[0]=`/usr/bin/top -cbn1 -u ss5 | grep $process_name | grep -v grep | /bin/awk '{ print $9 }'`
fi

OLDIFS=$IFS
IFS=$'\n'
highest_value=`echo "${cpu[*]}" | sort -nr | head -n1`
IFS=$OLDIFS

logger -s "highest_value: $highest_value"
logger -s "cpu_count: ${#cpu[@]}"

for cpu in ${cpu[@]}
do
        cpu=$(printf "%.0f" $cpu)
        highest_value=$(printf "%.0f" $highest_value)
        logger -s "inside cpu: $cpu and max_cpu_threshold: $max_cpu_threshold"
        if [[ $cpu -gt $max_cpu_threshold && $cpu -eq $highest_value ]]; then
                logger -s "inside something must be wrong with load.."
                if [[ $process_name == "squid" ]];then
                        /bin/sed -i -e 's/^access_log none/#&/' /opt/squid/etc/squid.conf
                        logger -s "/bin/sed -i -e 's/^access_log none/#&/' /opt/squid/etc/squid.conf"
                        /etc/init.d/squid restart
                elif [[ $process_name == "ss5" ]];then
                        logger -s 'SS5_OPTS=" -u ss5 -b 0.0.0.0:9999 -t"' > /etc/sysconfig/ss5
                        echo 'SS5_OPTS=" -u ss5 -b 0.0.0.0:9999 -t"' > /etc/sysconfig/ss5
                        /etc/init.d/ss5 restart
                fi
                logger -s CPU usage for $process_name is way too high with $cpu\% we will restart the service through monit!
                exit 1
        else
                if [[ $(grep -cE '#access_log none' /opt/squid/etc/squid.conf) -ne 0 ]]; then
                        /bin/sed -i -e 's/#access_log none/access_log none/' /opt/squid/etc/squid.conf
                        >/opt/squid/var/logs/access.log
                        logger -s "#access_log none found inside squid config, restarting squid and disabling it now"
                        /etc/init.d/squid restart
                fi
                if [[ $(grep -cE '#SS5_OPTS=" -u ss5 -b 0.0.0.0:9999 -m -t"' /etc/sysconfig/ss5) -ne 0 || $(grep -cE 'SS5_OPTS=" -u ss5 -b 0.0.0.0:9999 -t"' /etc/sysconfig/ss5) -ne 0 ]];then
                        echo 'SS5_OPTS=" -u ss5 -b 0.0.0.0:9999 -m -t"' > /etc/sysconfig/ss5
                        >/var/log/ss5/ss5.log
                        logger -s "commented out -m parameter found in ss5 config, restarting ss5 and re-enabling it now"
                        /etc/init.d/ss5 restart
                fi
                #logger -s CPU usage for $process_name is in normal range with $cpu\%
        fi
done

exit 0
