#!/bin/sh

if [ "$#" -ne 1 ]; then
	echo "Usage: $0 <url>" 1>&2
	exit 1
fi
url="$1"

to=$(basename "$url")

count=0
what='fetching'
while :
do
	if [ "$count" -eq 20 ]; then
		echo "EE: excessive redirects" 1>&2
		exit 1
	fi
	count=$(($count+1))

	echo "II: $what $url"

	# Retry transient network failures (e.g. truncated transfers) a few
	# times, and never leave a partially-downloaded file behind -- it would
	# fool the caller's file-presence check and the corrupt archive would
	# then fail at extraction time instead of being re-fetched.
	rm -f "$to" "$to.hdr"
	curl --silent --fail --show-error --retry 5 --retry-all-errors \
		--retry-delay 5 "$url" -o "$to" -D "$to.hdr" || {
		rm -f "$to" "$to.hdr"
		exit 1
	}
	redirect=$(awk '/^Location: / {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2); print $2;}' "$to.hdr")
	[ -z "$redirect" ] && break
	what='  following'

	url=$(echo "$redirect" | sed -e 's@https://launchpadlibrarian.net/@http://launchpadlibrarian.net/@')
	if [ "$redirect" != "$url" ]; then
		echo "II:   fixing $redirect"
	fi
done

exit 0
