#!/bin/sh -e

. /usr/share/debconf/confmodule

TRY_CONTINUE=
TRY_REPEAT=
while true; do
	case "$1" in
	    -c)
		TRY_CONTINUE=1
		shift
		;;
	    -r)
		TRY_REPEAT=1
		shift
		;;
	    -*)
		echo "$0: unrecognized or invalid option $1" >&2
		exit 1
		;;
	    *)
		break
		;;
	esac
done

url="$1"
dst="$2"
checksum="$3" # optional parameter

tmpdst="${dst:-/tmp/.test}.fetch-url.$$"
trap 'rm -f "$tmpdst"' EXIT HUP INT QUIT TERM

proto=${url%%://*}

. /usr/lib/fetch-url/$proto

protocol_fetch "$url" "$tmpdst" || exit $?

if [ "$checksum" ]; then
	filesum=$(md5sum "$tmpdst" | cut -d' ' -f1)
	if [ "$filesum" != "$checksum" ]; then
		echo "ERROR: checksum mismatch on '$url' (sum is '$filesum', rather than the expected '$checksum')" >&2
		exit 2
	fi
fi

[ -z "$dst" ] || mv -f "$tmpdst" "$dst"
# the trap above discards $tmpdst at this point
