#!/bin/bash

startTime=`date -d "-$1 hours" +%H:%M:%S`

if [[ -n $2 ]]
then
	endTime=`date -d "-$2 hours" +%H:%M:%S`
else
	endTime=`date +%H:%M:%S`
fi

#sourceData=/var/log/sysstat/sa07
cpuInput=/tmp/cpu.txt
cpuOutput=/tmp/cpu.png
cpuPlot=/tmp/cpu.gnuplot

if [[ ! -f `which sar` ]]
then
	yum >/dev/null && yum -y install sysstat || apt-get -y install sysstat
fi
	
LANG=C;sar -u -s ${startTime} -e ${endTime} | tail -n +3 | head -n -1 >${cpuInput}

cat >${cpuPlot}<<EOF
set xdata time
set timefmt "%H:%M:%S"
set grid
set title 'CPU Per.'
set xlabel 'TIME'
set xtics rotate by 0
set ylabel 'CPU'
set terminal png size 1600,800
set output "${cpuOutput}"
plot "${cpuInput}" using 1:3 title '%us' with linespoints lt 1 lw 1.5 pt 2 ps 1.2, \
     "${cpuInput}" using 1:5 title '%sy' with linespoints lt 2 lw 1.5 pt 2 ps 1.2, \
     "${cpuInput}" using 1:6 title '%wa' with linespoints lt 3 lw 1.5 pt 2 ps 1.2
EOF

gnuplot ${cpuPlot}
