#!/bin/bash
# boinc-stat.sh
# Copyright (C) 2005 Olivier Mehani <shtrom@ssji.net>
# 
# This script uses a processed version (see boinc-stat.xsl) of the
# client_stat.xml data file to report the current activity in one BOINC slot.
#
# Usage: boinc-stat.sh SLOT
# Example:
# $ ./boinc-stat.sh 2
# 29.381600	<-- current wu progression
# 99.1		<-- current cpu usage
# 6 days, 19:16	<-- uptime
# shmoldu	<-- hostname
# $ 
#
# I've tested it under GNU/Linux only, problems may arise on other systems
# because of the calls to ps, and the usage of /proc, mainly.
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

boincdir=/usr/local/boinc

uptime=/usr/bin/uptime
hostname=/bin/hostname
sed=/usr/bin/sed
bc=/usr/bin/bc
ps=/bin/ps
cat=/usr/bin/cat
grep=/usr/bin/grep
awk=/usr/bin/awk
head=/usr/bin/head
tail=/usr/bin/tail
xsltproc=/usr/bin/xsltproc

if [ $# -ne 1 ]; then
	echo "syntax: $0 SLOT" >&2
	exit 1
fi
slot=$1

mydir=`dirname $0`

function get_cpu()
{
	sum="0"
	for pid in `ps --no-headers -o pid -C $1`; do
		if ls -l "/proc/$pid/cwd" 2>/dev/null | grep -q "slots/$slot"; then
			sum="$sum + `ps --noheaders -o %cpu --pid $pid`"
		fi
	done

	echo "scale=4; $sum" | $bc -q

}

if [ -e $boincdir/client_state.xml ]; then
	out=`$xsltproc --param slot $slot $mydir/boinc-stat.xsl $boincdir/client_state.xml`
	if echo $out | grep -q "master_url"; then

		prog=`echo $out | sed -e "s-.*<fraction_done>\(.*\)</fraction_done>.*-scale=4;100*\1-" | bc -q`
		app=`echo $out | sed -e "s-.*<app>\(.*\)</app>.*-\1-"`
		sched_state=`echo $out|sed -e "s-.*<scheduler_state>\(.*\)</scheduler_state>.*-\1-"`
		cpu=`get_cpu $app`

		echo $prog
		echo $cpu
	else
		echo 0
		echo 0
	fi
else
	echo 0
	echo 0
fi	

$uptime | $sed -e "s/.*up *//" -e "s/, *[0-9]\+ user.*//"
$hostname
