#!/bin/bash
# A litte script that calculates the CPU load during a given time interval (t1-t2)

if [ "$1" == "" ]; then
    echo "You need to specify if you start or end the load calculation"
    exit 1
fi

if [ "$1" == "start" ]; then
    echo "Starting the CPU load calculation"
    rm cpuload_start
    rm cpuload_end
    head -n 6 /proc/stat | tr -s " " | cut -d " " -f 1,2,3,4,5  > cpuload_start
    exit 1
fi


if [ "$1" == "end" -o "$1" == "result" ]; then
    if [ "$1" == "end" ]; then
        echo "Ending the CPU load calculation"
        head -n 6 /proc/stat | tr -s " " | cut -d " " -f 1,2,3,4,5  > cpuload_end
    fi

    i=1
    exec 3<&0
    exec 0<cpuload_start
    while read line
    do
    v1=`echo $line | cut -d " " -f 2`
    v2=`echo $line | cut -d " " -f 3`
    v3=`echo $line | cut -d " " -f 4`
    v4=`echo $line | cut -d " " -f 5`

    start_user[$i]=$((${v1}+${v2}+${v3}))
    start_idle[$i]=${v4}
    i=$(($i+1))
    done
    exec 0<&3

    i=1
    exec 3<&0
    exec 0<cpuload_end
    while read line
    do
        caption[$i]=`echo $line | cut -d " " -f 1`
        v1=`echo $line | cut -d " " -f 2`
        v2=`echo $line | cut -d " " -f 3`
        v3=`echo $line | cut -d " " -f 4`
        v4=`echo $line | cut -d " " -f 5`
        end_user[$i]=$((${v1}+${v2}+${v3}))
    end_idle[$i]=${v4}
    i=$(($i+1))
    done
    exec 0<&3


    i=1
    while [ $i -lt 7 ]
    do
        delta_user[$i]=$((${end_user[i]}-${start_user[i]}))
    delta_idle[$i]=$((${end_idle[i]}-${start_idle[i]}))
    i=$(($i+1))    
    done

    i=1
    while [ $i -lt 7 ]
    do
     load[$i]=$(((${delta_user[i]}*100)/(${delta_user[i]}+${delta_idle[i]})))
         i=$(($i+1))
    done

    i=1
    while [ $i -lt 7 ]
    do
         echo -e "${caption[i]}:\t${load[i]}"
         i=$(($i+1))
    done

    exit 1
fi
