# Script that will calculate the notation for the node.
# Version 0.4
# Under GPL
#
# Jonathan "Arrouan" ROUZAUD-CORNABAS (rouzaud.jonathan@gmail.com)
#
# Change between 0.3 and 0.4
#   - Add of TMP_FILE
#   - Add of lock file to avoid two run at once.
#
# Change between 0.2 and 0.3
#   - SMP support.
#

# Lock file
LOCK_FILE=/tmp/cal_freenx.lock

# Check if script is already running
if ! [ -f $LOCK_FILE ]
then   

# Create lockfile.
touch $LOCK_FILE

# 
# Tempory file for calcul (bc).
TMP_FILE=/tmp/cal_freenx.file

# The 3 variables of load from uptime
LOADX=`cat /proc/loadavg | cut -d' ' -f1`
LOADY=`cat /proc/loadavg | cut -d' ' -f2`
LOADZ=`cat /proc/loadavg | cut -d' ' -f3`

# 100 sub 1st load variable 
echo "100-$LOADX" > $TMP_FILE
echo "quit" >> $TMP_FILE
LOADX1=`bc -q $TMP_FILE`

# 100 sub 2nd load variable
echo "100-$LOADY" > $TMP_FILE
echo "quit" >> $TMP_FILE
LOADX2=`bc -q $TMP_FILE`

# 100 sub 3rd load variable
echo "100-$LOADZ" > $TMP_FILE
echo "quit" >> $TMP_FILE
LOADX3=`bc -q $TMP_FILE`

# Add of the 3 load resultat of 100 sub load variable.
echo "$LOADX1+$LOADX2+$LOADX3" > $TMP_FILE
echo "quit" >> $TMP_FILE
LOADXX=`bc -q $TMP_FILE`

# Add of total memory and free memory
Rt=`cat /proc/meminfo | grep MemTotal | tr -s ' ' | cut -d' ' -f2`
Rd=`cat /proc/meminfo | grep MemFree | tr -s ' ' | cut -d' ' -f2`
echo "$Rt + $Rd" > $TMP_FILE
echo "quit" >> $TMP_FILE
Mt=`bc -q $TMP_FILE`

# NBCPU = number of CPU
NBCPU=`cat /proc/cpuinfo | grep ^processor | wc -l`

# CPU = Mhz of the CPU
CPU=`cat /proc/cpuinfo | grep "cpu MHz" | head -n1 | cut -d':' -f2 | cut -d' ' -f2`

# Number of Xorg already launch and running.
UNB=` ps aux | grep Xorg | grep -v grep | wc -l`

# Final calcul of the number of load.
echo "100 * $LOADXX + $Mt + ( $NBCPU * $CPU ) / 100 + $UNB * 100" > $TMP_FILE
echo "quit" >> $TMP_FILE
RES=`bc -q $TMP_FILE`


echo $RES

# Delete temporary file.
rm $TMP_FILE

# Delete lock file.
rm $LOCK_FILE

fi
