#GW Special
echo "special"

# 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://data.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://incoming.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
}

ifconfig
cd /root/code
cp -r * /glacsweb/data
cp cameras.conf borecam.conf
./grab_picture.py
fetch_file "camera.py" "7d68dd98b6d695894cc03026abd18193" "/root/code" "+w"
fetch_file "functions.sh" "1bba5d5f4d4f50c0875ea4562b14df1d" "/root/code" "+w"
echo "end special"
