#!/bin/sh

# Determine the location of log file for stats
LOG="/etc/snmp/cpu.log"
# Time after which the log file is detected as not relevant
LOG_LIVE_TIME=20

# Check for expired stat files
if [ -e $LOG ]; then

	current_file=`find $LOG -cmin -$LOG_LIVE_TIME`
	if [ -n "$current_file" ]; then
		# echo "Current log file found"
		:
	else
		# echo "Expired log file found"
		rm -f $LOG
		touch $LOG
	fi
else
	touch $LOG
fi

# Count words to check any relevant data
words=$(wc -w $LOG | awk '{print $1}')
if [ "$words" -eq "0" ]; then
	echo "cpu idle for 1min: nun"
	echo "cpu idle for 5min: nun"
	echo "cpu idle for 15min: nun"
        exit 0
fi

# Format of stats file is: total_time idle_time
# why 16? its because we calculate from 0 to 15
# but sed calculate stings from 1 to inf.
for index in {1..16}; do
    line=`cat $LOG | sort -r | sed "${index}q;d"`
    total_time[index]=`echo $line | awk '{print $1}'`
    idle_time[index]=`echo $line | awk '{print $2}'`
done

for i in 2 6 16; do
	((idle=${idle_time[i]}-${idle_time[1]}))
	((total=${total_time[i]}-${total_time[1]}))
	((cpu= (idle*100)/total))
	((min=$i-1))
	echo "cpu idle for ${min}min: $cpu"
done

exit 0

