#!/bin/tcsh -f

source ~maison/sensors.env

setenv TMPFILE `mktemp /tmp/get_temp.XXXXXX`

foreach id (${SENSID})
echo -n "Downloading ${id}.log ... "
lynx -source http://192.168.1.10/data/log/${id}.log > ${TMPFILE}
setenv ERROR `grep "404 " ${TMPFILE}`

if { test -z "${ERROR}" } then
    cp ${TMPFILE} old/${id}_`date +"%Y-%m-%d-%H:%M:%S"`
    mv ${TMPFILE} ${id}.log
else
    rm -f ${id}.log
    echo "error 404: id=$id" 
endif
echo "Done."
end
rm -f ${TMPFILE}

rm -f t1.xml
rrdtool dump ~maison/rrd/temperature.rrd > t1.xml

if { test ! -s "t1.xml" } then
    echo "can't dump rrd-database"
    exit 0
endif

#make a copy
cp t1.xml t.xml


foreach id (${SENSID})
if { test -s "${id}.log" } then
	echo "update $id"
	#./rrd_replace t1.xml t2.xml ${id}.log
	./rrd_replace -r -i t1.xml -o t2.xml -d ${id}.log -c ${id}
	mv t2.xml t1.xml
endif
end


su - maison -c "~maison/init.d/maison stop"

rm -f ~maison/rrd/temperature.rrd.new
#cp -p ~maison/rrd/temperature.rrd ~maison/rrd/temperature.rrd.org
rrdtool restore t1.xml ~maison/rrd/temperature.rrd.new
if { test -s ~maison/rrd/temperature.rrd.new } then
    mv ~maison/rrd/temperature.rrd.new ~maison/rrd/temperature.rrd
    chown maison ~maison/rrd/temperature.rrd
else
    echo "Error replace rrd-file"
endif

#echo "rrdtool restore t1.xml ~maison/rrd/temperature.rrd.new"
#echo "mv ~maison/rrd/temperature.rrd.new ~maison/rrd/temperature.rrd"

su - maison -c "~maison/init.d/maison start"

