#!/bin/sh
echo "running special"
cd /home/root
echo "changed to home root"

# 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 -q http://env.ecs.soton.ac.uk/glacsweb/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://env.ecs.soton.ac.uk/glacsweb/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
}

run_cmd "rm functions.sh"

fetch_file "functions.sh" "38ec6bba9412ce1889ede787c0acbec3" "/home/root" "755"
echo "sourcing functions.sh"
source "functions.sh"
echo "sourced"
