#! /bin/bash

# ukázka skriptu pro zozbrazení aktivity systému pomocí sar
# použití: gsar [prodleva] [počet měření]

# zaznamenáme statistiky pomocí sar(1)
DELAY=${1:-1};NUM_RECORDS=${2:-5};

sar -o /tmp/sarlog$$ $DELAY $[$NUM_RECORDS]
sar -f /tmp/sarlog$$ | sed -e 1,3d -e '$d' -e 's/ \+/ /g' -e '/^$/{N
d
}' > /tmp/sarlog$$.cpu
sar -w -f /tmp/sarlog$$ | sed -e 1,3d -e '$d' -e 's/ \+/ /g' -e '/^$/{N
d
}' > /tmp/sarlog$$.csw
sar -r -f /tmp/sarlog$$ | sed -e 1,3d -e '$d' -e 's/ \+/ /g' -e '/^$/{N
d
}' > /tmp/sarlog$$.mem
sar -b -f /tmp/sarlog$$ | sed -e 1,3d -e '$d' -e 's/ \+/ /g' -e '/^$/{N
d
}' > /tmp/sarlog$$.io

# zjistíme rozsahy grafů
MAX_CS=$(cut -f 2 -d ' ' < /tmp/sarlog$$.csw | sort -n -r | head -n 1);
MAX_IO_IN=$(cut -f 5 -d ' ' < /tmp/sarlog$$.io | sort -n -r | head -n 1);
MAX_IO_OUT=$(cut -f 6 -d ' ' < /tmp/sarlog$$.io | sort -n -r | head -n 1);
MAX_IO=`echo "$MAX_IO_IN+$MAX_IO_OUT" | bc`;
MEM_TOTAL=`grep MemTotal /proc/meminfo | sed 's/[a-zA-Z: ]//g'`;
START_TIME=$(head -n 1 /tmp/sarlog$$.csw | cut -f 1 -d ' ');
STOP_TIME=$(tail -n 1 /tmp/sarlog$$.csw | cut -f 1 -d ' ')

# skript pro gnuplot
cat <<EOF | gnuplot       

# nejprve obecné nastavení
set terminal gif size 640,480; set output "/tmp/sarlog$$.gif"             
set size 1,1; set origin 0,0; set multiplot                              
set grid; set xrange [0:$NUM_RECORDS]; set nokey                                  

# 1. graf - vytížení procesoru
set size 1,0.25; set origin 0,0                             
set yrange [0:100]                        
set xdata time; set timefmt "%H:%M:%S"
set xrange ["$START_TIME":"$STOP_TIME"]
set format x "%H:%M:%S"
set label "CPU activity [%]" at screen 0.5,0.2 center       
plot "/tmp/sarlog$$.cpu" using 1:(\$3+\$4+\$5) with lines   

# 2. graf - paměť (použitá celkem - (cacheˇ+ buffer))
set size 1,0.25; set origin 0,0.25
set yrange [0:$MEM_TOTAL]; set ytics 0,$MEM_TOTAL/5,$MEM_TOTAL 
set xdata time; set timefmt "%H:%M:%S"
set xrange ["$START_TIME":"$STOP_TIME"]
set format x "%H:%M:%S"
set label "Used memory [kb]" at screen 0.5,0.45 center
plot "/tmp/sarlog$$.mem" using 1:(\$3-(\$6+\$7)) with lines

# 3. graf - přepnutí kontextu
set size 1,0.25; set origin 0,0.5
set autoscale ymax; set ytics $MAX_CS/5
set xdata time; set timefmt "%H:%M:%S"
set xrange ["$START_TIME":"$STOP_TIME"]
set format x "%H:%M:%S"
set label 1 "Context switches [csw/s]" at screen 0.5,0.7 center
plot "/tmp/sarlog$$.csw" using 1:2 with lines

# 4. graf - i/o statistiky
set size 1,0.25; set origin 0,0.75
set autoscale ymax; set ytics $MAX_IO/5
set xdata time; set timefmt "%H:%M:%S"
set xrange ["$START_TIME":"$STOP_TIME"]
set format x "%H:%M:%S"
set label "I/O activity [blocks/s]" at screen 0.5,0.95 center
plot "/tmp/sarlog$$.io" using 1:(\$5+\$6) with lines

EOF
# display using xv
xv /tmp/sarlog$$.gif


