#!/usr/local/bin/bash
# Script to killall nautilus if it hangs (run it from cron)
# Checks 4 times with a delay of 20 seconds
# ind if every time nautilus takes more than $max_cpu_usage value then killall's active nautilus
# The script is Messy but at least working!
# Usage: set on cron 
# something like 0,59 * * * * /usr/sbin/restart_nautilus.sh >/dev/null 2>&1
# Bless The Lord and Glory His Holy Name! :)

max_cpu_usage='35';
# sleep delay between checks for nautilus
sleep_time='20';
# check how many times
check_times='4';

arg0=$0;
#cycle_cnt=$(ps axu|grep -i nautilus|grep -v grep| grep -v $arg0 | wc -l | awk '{ print $1 }')

for L in $(jot $check_times); do
a=0; r=3;

sleep $sleep_time;

cycle_cnt=$(ps axu|grep -i nautilus|grep -v grep| grep -v $arg0 | wc -l | awk '{ print $1 }');

for i in $(jot $cycle_cnt); do 
a=$(( $a + 1 )); r=$(( $r - 1 )); 
line=$(ps aux |grep -i nautilus|grep -v grep | grep -v $arg0 | head -n $a| tail -n $r); 

cpu_time=$(echo $line| awk '{ print $3 }'); 
pid=$(echo $line | awk '{ print $2 }');
cpu_time=$(echo $cpu_time | sed -e "s#\.# #g"| awk '{ print $1 }');

if [ "$cpu_time" -gt "$max_cpu_usage" ]; then
pid_to_kill="$pid";
pid_of=$(echo $pid |wc -l);
fi

done

if [ "${pid_of}" ]; then
pids[$L]="yes"
fi


done

may=0;
for Z in $(jot $check_times); do

if [ "${pids[$Z]}" == "yes" ]; then
may=$(( $may + 1));
#echo $may;
else 

exit 0;

fi

if [ "$may" == "$check_times" ]; then
kill -HUP $pid_to_kill;
fi

done
