#!/bin/bash

# BOINC status monitor (developed from setitime.sh)
# by TeknoHog at iki.fi

basedir=~/distr.projects/BOINC

compute() {
    echo "$1" | bc -l
}

xml_find() {
    grep -sr $1 $2 | \
	sed -e "s/<[a-z/_]*>//g"
}

boinc_stats() {
    statefile=$basedir/client_state.xml

    if [ ! -f $statefile ]; then
	return 1
    fi

    #names=(`xml_find project_name $statefile`)
    urls=(`xml_find project_master_url $statefile`)
    prog_list=(`xml_find fraction_done $statefile`)
    cpu_list=(`xml_find current_cpu_time $statefile`)
}

print_info() {

    echo $url

    # totals completed can usually be found on the website...

    percent=`compute "100 * $prog"`
    echo $percent "% of current unit processed"

    if [ $percent != 0 ]; then 

	cputotal=`compute "$cpu / $prog"`
    
	remaining=`compute "$cputotal * (1 - $prog)"`
# cut off decimals for date computation, as bc doesn't _scale_ as expected
	remaining=${remaining/\.[0-9]*/}
    
# Using "date" to compute total time in hh:mm:ss is hard if it goes over one day, as there is no day zero! Use decimal hours for now...
	
	echo "Estimated total:" `compute "scale=3; $cputotal / 3600"` hours 
	echo "Estimated finish:" `date  +"%b %d %T" -d "+$remaining seconds"`
    fi
}

loop_info () {
    boinc_stats || exit

    num_clients=${#prog_list[*]}
    
    i=0

    for i in `seq 0 $((num_clients - 1))`; do
	cpu=${cpu_list[$i]}
	prog=${prog_list[$i]}
	#name=${names[$i]}
	url=${urls[$i]}

	print_info

	# newline for separation between different items, but not at the end
	if [ $i -lt $((num_clients - 1)) ]; then
	    echo
	fi
    done
}

loop_info


