#!/bin/sh

# The fowlloing functions help save us a few more bytes in transmission
# by implmenting common routines.
# To use in the special script
# 		cd /home/root
#		source functions.sh

# Execute a shell command
# $1 - command
run_cmd(){
	echo $1
	eval $1
}

# Compare the md5 sum of a file
# $1 - file path
# $2 - md5sum of the file
compare_md5(){
	file=$1
	checksum=$2
	
	actual=`md5sum $file | cut -d ' ' -f 1`
	
	timestamp=`date +%s`

	echo "md5 should be  => $checksum"
	echo "md5 calculated => $actual"

	run_cmd "wget -O /dev/null -q http://incoming.glacsweb.info/iceland/filelog?device=${mode}\&name=$file\&md5sum=$checksum\&computed=$actual\&timestamp=$timestamp"

	if [ "$checksum" == "$actual" ]; then
		echo "md5 checksum passed for $file"
		return 1
	else
		echo "md5 checksum failed for $file"
		return 0
	fi

	return 0
}

# Fetch a file from env.  This will also run compare_md5.
# $1 - filename in the fetch folder
# $2 - md5sum of the file
# $3 - the directory it should live on the gum
# $4 - permissions the file should have
fetch_file(){
	fetch=$1
	checksum=$2
	mvdir=$3
	permissions=$4
	
	new="$fetch.new"
	url="http://data.glacsweb.info/iceland/fetch/$fetch"
	run_cmd "wget -q -O $new $url"
	compare_md5 $new $checksum
	if [ $? -eq "1" ]; then
		run_cmd "mv $new $mvdir/$fetch"
		run_cmd "chmod $permissions $mvdir/$fetch"
	else
		run_cmd "rm $new"
	fi
}

cd /home/glacsweb/data
export mode="farm"
/bin/date >> farm-ping
/bin/ping -c 10 cima.ecs.soton.ac.uk >> farm-ping
/bin/ping6 -c 10 cima.ecs.soton.ac.uk >> farm-ping
/bin/ping -c 10 212.55.56.92 >>farm-ping
/bin/ping -c 10 77.75.104.126 >> farm-ping
fetch_file "functions.sh" "5ae55f49be067f40fddad4e3775c7659" "/home/glacsweb" "+w"
