#!/bin/bash
# Copyright (c) 1997 Andrew G. Morgan <morgan@physics.ucla.edu>
# Copyright (c) 1997 The Regents of the University of California
#
# This is the go daemon
#
if [ $# -eq 0 ]; then
    ($0 -bg 2>&1) > /dev/null &
    exit
fi
## These files of nice values for each user (there should be a
## wish script to maintain this
local_nice=/etc/niceuser.conf
remote_nice=/cluster/niceuser.conf
default_nice=4
update_interval=180
#

nice_computer () {
#
# First a sorted list of the currently known (non-root) processes
#
    list_procs=`ls -l /proc | grep -v root | sort | cut -c 56-`
#
# loop through processes and interact with running ones
#
    for p in $list_procs ;
    do
#
	if [ -d /proc/$p ]; then
	    user=`ls -dl /proc/$p|cut -c 16-23 2>/dev/null`
# $p may not be running
	    if [ $? -ne 0 ]; then
		continue
	    fi
	    if [ "$user" != "$lastuser" ]; then
		known=`fgrep $user $nice_file|tail -1`
		if [ -z "$known" ]; then
# skip unlisted users
		    known="$user:$default_nice"
		fi
		minnice=`echo $known|cut -d: -f 2`
		if [ -z "$minnice" ]; then
		    continue
		fi
		lastuser=$user
	    fi
# identify the minimum nice value for the user
	    state=`cat /proc/$p/stat`
# $p may not be running any longer..
	    if [ $? -eq 0 ]; then
		echo $state|cut -d' ' -f 3|grep R 2>&1 > /dev/null
		if [ $? -eq 0 ]; then
		    niceval=`echo $state |cut -d' ' -f 19`
#		echo -e "$p:\tis running with nice $niceval"
		    if [ -z "$niceval" ]; then
			continue
		    fi
		    if [ $niceval -lt $minnice ]; then
#		    echo "Should renice $p from $niceval to $minnice"
			renice $minnice $p > /dev/null 2>&1
		    fi
		fi
	    fi
	fi
    done
}

## Bail out if there are no restrictions in place
#
if [ -f $local_nice ]; then
    nice_file=$local_nice
elif [ -f $remote_nice ]; then
    nice_file=$remote_nice
else
# No available policy for nicing users
    exit 0
fi

#
# This is the actual program loop (short runs will typically avoid
# being niced)
#

while [ -z "$hell_frozen" ]; do
    nice_computer
    sleep $update_interval
done

exit 0
