#!/bin/bash

# If a process uses more than this percent of CPU, bump its priority down
# a step (to a maximum of MAXNICE)
#
TOOMUCHCPU=40
MAXNICE=19

# Processes using less than this percent of CPU get their priority raised
# up (to a minimum of MINNICE)
#
NICEAMOUNTOFCPU=10
MINNICE=0

# Host name
MYNAME="`hostname`"

# Find the heaviest CPU user that's a at a priority less than 10 (see
# above).  This process will be our BADBOY.
#
BADBOY="`ps -ewo '%U %n %p %C %c'		      | \
	  egrep -vi '^USER |^root '		      | \
	  sort --key 4 --reverse		      | \
	  head -1`"

if [ ".$BADBOY" = '.' ]; then
  : do nothing
else
    BADNICEVAL=`echo "$BADBOY" | awk '{ print $2 }'`;
    if [ "$BADNICEVAL" -lt "$MAXNICE" ]; then
	BADPERCENT=`echo "$BADBOY" | awk '{ print $4 }' | sed 's/\.[0-9]*$//'`;
	if [ "$BADPERCENT" -gt "$TOOMUCHCPU" ]; then
	    BADPRIORITY=`echo "$BADBOY" | awk '{ print $2 }' | sed 's/\+//'`;
	    BADPID=`echo "$BADBOY" | awk '{ print $3 }'`;
	    BADNAME=`echo "$BADBOY" | awk '{ print $5 }'`;
	    echo "$0: Lowering priority of CPU hogging process on $MYNAME: $BADPID ($BADNAME)" 1>&2
	    renice "`expr $BADPRIORITY + 1`" "$BADPID" 2>&1
	fi
    fi
fi

# Find lightest CPU user that's running at a priority higher than
# zero.  This will be our GOODBOY.
#
GOODBOY="`ps -ewo '%U %n %p %C %c'			 | \
	  egrep -vi '^USER |^root  '			 | \
	  egrep '^[^ ]+ +\+?[1-9]'			 | \
	  sort --key 4					 | \
	  head -1`"

if [ ".$GOODBOY" = '.' ]; then
  : do nothing
else
    GOODNICEVAL=`echo "$GOODBOY" | awk '{ print $2 }'`;
    if [ "$GOODNICEVAL" -gt "$MINNICE" ]; then
	GOODPERCENT=`echo "$GOODBOY" | awk '{ print $4 }' | sed 's/\.[0-9]*$//'`;
	if [ "$GOODPERCENT" -lt "$NICEAMOUNTOFCPU" ]; then
	    GOODPRIORITY=`echo "$GOODBOY" | awk '{ print $2 }' | sed 's/\+//'`;
	    GOODPID=`echo "$GOODBOY" | awk '{ print $3 }'`;
	    GOODNAME=`echo "$GOODBOY" | awk '{ print $5 }'`;
	    echo "$0: Raising priority of CPU-nonintensive process on $MYNAME: $GOODPID ($GOODNAME)" 1>&2
	    renice "`expr $GOODPRIORITY - 1`" "$GOODPID" 2>&1
	fi
    fi
fi

