#!/bin/bash

source /etc/profile

if [[ ! -d /var/run/throttler ]] ; then
	mkdir -p /var/run/throttler
fi

processes=`vps ax | grep '\(updatedb\|tripwire\|samhain\|aide\|rsync\|cp \|rm \|find \|awstats.pl\|webalizer\|rkhunter\|cc1\|logwatch\|emerge\|perl-cleaner\|revdep-rebuild\|minerd\|pprocessqueue\|mysqldump\|ossec\)' | grep -v '\(grep\|ionice\|scp\)' | grep -v \'$0\' |  awk '{print $1 "|" $2 "|" $3 "|" $7 "|" $8 "|"  $9 "|"  $10 "|"  $11 "|"  $12 }'`
for my_process in $processes ; do
	my_pid=`echo $my_process |  cut -d '|' -f 1 `
	context=`echo $my_process | cut -d '|' -f 2 `
	# These processes use throttler with the SIGSTOP method
	my_command=`echo $my_process | grep -v scp | grep '\(updatedb\|tripwire\|samhain\|aide\|rsync\|cp \|rm \|find \|awstats.pl\|webalizer\|rkhunter\|cc1\|logwatch\|perl-cleaner\|revdep-rebuild\|minerd\|pprocessqueue\|mysqldump\|ossec\)' | cut -d '|' -f 4,5 | sed 's/|/ /'`
	if [[ "$my_command" != "" ]] ; then
		renice -n 19 -p $my_pid
		ionice -c 2 -n 7 -p $my_pid
		throtther_flag=N
		if [[ -f /var/run/throttler/$my_pid ]] ; then
			throtther_flag=Y
			if [[ ! -d /proc/`cat /var/run/throttler/$my_pid` ]] ; then
				rm -f /var/run/throttler/$my_pid
				throtther_flag=N
			fi
		fi
		if [[ $throtther_flag == N ]] ; then
			throttler $context $my_pid &
			echo $! > /var/run/throttler/$my_pid
		fi
	fi
#	# These processes use throttler with the FREEZER method
#	my_command=`echo $my_process | cut -d '|' -f 4,5 | sed 's/|/ /' | grep -v scp | grep '\(1234567890\)'`
#	if [[ "$my_command" != "" ]] ; then
#		vcontext --migrate --xid 1 -- ionice -c 2 -n 7 -p $my_pid
#		throtther_flag=N
#		if [[ -f /var/run/throttler/$my_pid ]] ; then
#			throtther_flag=Y
#			if [[ ! -d /proc/`cat /var/run/throttler/$my_pid` ]] ; then
#				rm -f /var/run/throttler/$my_pid
#				throtther_flag=N
#			fi
#		fi
#		if [[ $throtther_flag == N ]] ; then
#			throttler $my_pid &
#			echo $! > /var/run/throttler/$my_pid
#		fi
#	fi
	# We do not throttle these processes: \|emerge
done

processes=`vps ax | grep '\(lzma\|gzip\|bzip2\|pg_dump\|amavisd\|assp\|clamd\|spamd\)' | grep -v '\(grep\|ionice\)' | grep -v \'$0\' | cut -b 1-5`
for my_pid in $processes ; do
	renice -n 19 -p $my_pid
	ionice -c 2 -n 7 -p $my_pid
done

processes=`vps ax | grep '\(mysqld\|python2.4\)' | grep -v '\(grep\|ionice\)' | grep -v \'$0\' | cut -b 1-5`
for my_pid in $processes ; do
	renice -n 15 -p $my_pid
	ionice -c 2 -n 6 -p $my_pid
done

processes=`vps ax | grep '\(postgres\)' | grep -v '\(grep\|ionice\)' | grep -v \'$0\' | cut -b 1-5`
for my_pid in $processes ; do
	renice -n 11 -p $my_pid
	ionice -c 2 -n 5 -p $my_pid
done

JOBS=`jobs`
if [[ "$JOBS" != "" ]] ; then
	disown
fi
