#!/bin/sh

# Upload files to a webdav storage,
# check them by an MD5 Hash
# and remove the local copy afterwards.


if [ "$1" == "-h" ];
	then
	echo "Syntax:"
	echo "upload.sh [Local File Location] [Remote File Location] [username:password]"

	elif [ $1 = $2 ];
	then
	echo "Source and Target are the same"
	echo "No Arguments provided!"

	

	else
	
	STAMP=$(date "+%Y%m%d-%H%M%S")
	
	echo $STAMP
	
	# get the online images' MD5
	pre_online_md5=$(curl $2 -k -u $3 | md5sum | awk '{print $1}')

	# get the local images' MD5
	pre_local_md5=$(md5sum "$1" | awk '{print $1}')

	# compare both MD5s
	echo "$pre_online_md5"
	echo "$pre_local_md5"
	
	#check if the file already exists
	if curl --head -u $3 --fail $2 -k;
	then
	## it exists
	
	echo "FILE ALREADY EXISTS"
	
		# Check if it is the same already
		if [ "$pre_online_md5" != "$pre_local_md5" ];
		then
		# FILES DIFFER FROM EACH OTHER
			# if not move the online file
			
			echo "RANAMING FILE TO $2.$STAMP"
			
			curl -u $3 -k -X MOVE --header "Destination:$2.$STAMP" $2
		fi
	fi
	
	# IF THERE WAS ANOTHER IMAGE, NOW IT SHOULD BE RENAMED
	
	echo "UPLOAD FILE"
	curl -u $3 -T $1 $2 -k
	
	# get the online images' MD5
	online_md5=$(curl $2 -k -u $3 | md5sum | awk '{print $1}')

	# get the local images' MD5
	local_md5=$(md5sum "$1" | awk '{print $1}')

	# compare both MD5s
	echo "$online_md5"
	echo "$local_md5"

	if [ "$online_md5" == "$local_md5" ];
	# Remove the original Image if successful
	then
		echo "Uploaded successfully!"

		# Remove Original
		rm $1

		# Fallback routine if not successful
		else
		echo "Upload failed!!"
	fi
fi
