#!/usr/bin/bash
tmp=/tmp/$$

function getLocation() {
	curl -I --silent $1 | while read line
	do
		if [[ "$line" =~ ^HTTP ]]; then
			echo $line > $tmp-status
		fi

		if [[ "$line" =~ ^[Ll]ocation: ]]; then
			echo $line > $tmp-location
		fi
	done
	
	if [ ! -e $tmp-location ]; then
		echo $1
		return
	fi

	location=$(echo $(cat $tmp-location) | sed -e "s/^[Ll]ocation: \?//")
	rm -f $tmp-location
	status=$(cat $tmp-status)
	rm -f $tmp-status

	if [[ "$status" =~ ^HTTP/.*\.*.*\ 30. ]]; then
		getLocation $location
		return
	fi

	echo $location
}

getLocation $1
rm -f $tmp-*