#!/bin/sh


# ---- INIT ----

# Number of parallel threads your system can schedule
NUM_CORE=2  

# Boinc projects running on this box ('|' as separator)
PROJ="seti|simap|rosetta|einstein|lhc" 



# ---- MAIN ----
echo
echo "GiPOCO Boinc Affinity Manager"
echo
OLD_PID=0
OVERLAP=0
OVERRUN=0
CNT=0
CNTS=0
FOUND=`ps ax | egrep \($PROJ\) | grep -v grep | grep RN | awk '{print $1}' | wc -l`
if [ "$FOUND" -gt 1 ]
then
for ID in `ps ax | egrep \($PROJ\) | grep -v grep | grep RN | awk '{print $1}'`
do
	
	let "DELTA=OLD_PID-ID"
	if [ "$DELTA" -lt 0 ]
	then
		let "DELTA=DELTA*-1"
	fi
	if [ "$DELTA" -lt 5 ]
	then
		OVERLAP=1
	fi
	let "CNT=CNT+1"
	let "CNTS=CNTS+1"
	if [ "$CNT" -gt "$NUM_CORE" ]
	then
		OVERRUN=1
	fi
	echo "==> $ID found !!"
        for ID2 in `ps ax | egrep \($PROJ\) | grep -v grep | awk '{print $1}'`
	do
		let "SUB=ID-ID2"
		if [ "$SUB" -lt 0 ]
		then
			let "SUB=SUB*-1"
		fi
		if [ "$SUB" -lt 4 ]
		then
			OLD_CORE=`taskset -p $ID2 | awk '{print $6}'`
			taskset -p $CNT $ID2 2>&1 >/dev/null
			NEW_CORE=`taskset -p $ID2 | awk '{print $6}'`
			PROC=`ps ax | grep $ID2 | grep -v grep | awk '{print $5}'`
			echo "PID:$ID2 TYPE:${PROC:0:4} Delta:$SUB - Affinity OLD:$OLD_CORE NEW:$NEW_CORE"
		fi
	done
	echo "DONE."
	echo
	echo "-----------"
	echo
	let "OLD_PID=ID"
done 
if [ "$OVERRUN" -gt 0 ]
then
	echo
	echo "WARNING: MORE THREADS THAN CORES !!"
	echo
	CNT=1
fi
if [ "$OVERLAP" -gt 0 ]
then
	echo
	echo "WARNING: OVERLAPPING OCCURRED !!"
	echo "(Run again after next workunit completed)"
	echo
fi
if [ "$CNTS" -lt "$NUM_CORE" ]
then
	echo
	echo "WARNING: SOME CORES ARE IN IDLE !!"
	echo
fi
else
	echo "ERROR: Boinc processes NOT found !!"
	echo
fi

