#
# sysload.sh: log system load
#             (called from cron table)
#
# Written by Leor Zolman, 6/17/91
#
# usage:
#   sysload.sh daily    (run periodically throughout the day)
#   sysload.sh final    (run once at the end of the day)
#
# When $1 is "daily": adds a line to DAYLOG with the current 15-minute
#   load average.
#
# When $1 is "final": computes average of all daily entries in DAYLOG. An
#   entry noting this average is appended to AVGLOG. The contents of DAYLOG
#   and the average are then appended  to LOADLOG,  and DAYLOG is deleted.
#   Then, if this is Friday, the average of the 5 daily averages is
#   also computed and appended to AVGLOG.
#
#

debug=N
ADMINGRP=tech           # System administration group id on your system

if [ $debug = N ]; then
    DAYLOG=/u3/General/Ltmp/sysload.day
    LOADLOG=/u3/General/Ltmp/sysload.log
    AVGLOG=/u3/General/Ltmp/sysload.avg
else
    DAYLOG=day
    LOADLOG=log
    AVGLOG=avg
fi

[ $# -ne 1 ] && echo "usage: $0 {daily | final}" >&2 && exit 1

case $1 in 
    daily)
        if [ ! -r $DAYLOG ]; then
            touch $DAYLOG
            chmod 664 $DAYLOG
            chgrp $ADMINGRP $DAYLOG
        fi
        echo `date +"%a %D %T"`: `uptime | 
        awk '{
            txt = $(NR)
            if (substr(txt, length(txt), length(txt)) == ",")
                txt = substr(txt, 1, length(txt)-1)
            print txt
        }'` >>$DAYLOG
        break;;

    final)
        [ ! -r $DAYLOG ] && echo "$0: Cannot open $DAYLOG" >&2 && exit 1
        if [ ! -r $LOADLOG ]; then
            touch $LOADLOG
            chmod 664 $LOADLOG
            chgrp $ADMINGRP $LOADLOG
        fi
        if [ ! -r $AVGLOG ]; then
            touch $AVGLOG
            chmod 664 $AVGLOG
            chgrp $ADMINGRP $AVGLOG
        fi
        tmp=`tmpname sld`
        echo "`date +\"%a %D\"`: \c" >$tmp
        awk '{
            total = total + $4
            count = count + 1
            }
            END {
                printf("\tAverage for the day: %5.2f\n", total / count)
            }' <$DAYLOG >>$tmp

        cat $DAYLOG >>$LOADLOG      # update full log
        cat $tmp >>$LOADLOG
        echo >>$LOADLOG

        cat $tmp >>$AVGLOG          # update average only log
        if [ `date +%w` = 5 ]; then # if friday, then
            tail -5 $AVGLOG |
                awk '{
                    total = total + $7 }
                    END { printf "\t\tAVERAGE FOR THE WEEK: %5.2f\n", 
                            total / 5
                    }' >> $AVGLOG   # append weekly average
            echo >>$AVGLOG          # blank line between weeks
        fi

        rm $DAYLOG $tmp             # remove daily temp file
        ;;

    *) echo "usage: $0 {daily | final}" >&2  && exit 1;;
esac
