#!/bin/bash
set -e

mkdir -p "${DOCKER_TARBALLS:=../tarballs}"

# MUST STAY IN SYNC WITH LIST IN "debian/rules"
multiOrigGopkgs=(
	github.com/docker/libnetwork
)

pkg="$(dpkg-parsechangelog -SSource)"
ver="$(dpkg-parsechangelog -SVersion)"
origVer="${ver%-*}" # strip everything from the last dash
origVer="$(echo "$origVer" | sed -r 's/^[0-9]+://')" # strip epoch
upstreamVer="${origVer%%[+~]ds*}"
origTarballPrefix="${DOCKER_TARBALLS}/${pkg}_${origVer}.orig"
unprunedTarballPrefix="${DOCKER_TARBALLS}/${pkg}_${upstreamVer}.orig"

if command -v curl &> /dev/null; then
	curl='curl -fsSL'
elif command -v wget &> /dev/null; then
	curl='wget -qO-'
else
	echo >&2 'error: missing "curl" or "wget" - install one or the other'
	exit 1
fi

get_hack_vendor() {
	for path in hack/vendor.sh project/vendor.sh; do
		if [ -e "${origTarballPrefix}.tar.gz" ]; then
			# if we have the main orig tarball handy, let's prefer that
			if tar -xzOf "${origTarballPrefix}.tar.gz" --wildcards '*/'"$path"; then
				return
			fi
		else
			# but fall back to grabbing it raw from github otherwise
			if $curl "https://raw.githubusercontent.com/docker/docker/v${upstreamVer}/$path"; then
				return
			fi
		fi
	done
}

ret=0
for gopkg in "${multiOrigGopkgs[@]}"; do
	commit="$(get_hack_vendor | awk '$1 == "clone" && $2 == "git" && $3 == "'"$gopkg"'" { print $4 }')"
	if [ "$commit" ]; then
		origTar="$unprunedTarballPrefix-$(basename "$gopkg").tar.gz"
		$curl "https://$gopkg/archive/$commit.tar.gz" > "$origTar"

		echo "successfully fetched $origTar"
		echo "  (from $gopkg commit $commit)"

		"$(dirname "$(readlink -f "$BASH_SOURCE")")/../repack.sh" --upstream-version "$upstreamVer" "$origTar"
	else
		echo >&2 "error: cannot find $gopkg commit!"
		ret=1
	fi
done
exit $ret
