#!/bin/sh

if [ -n "${1}" ]; then
	CURDIR="${1}"
else
	echo "ERROR: not called with \$(CURDIR) parameter" >&2
	exit 1
fi

# parse versions
VERSION="$(dpkg-parsechangelog -l${CURDIR}/debian/changelog | sed -ne 's,^Version: *\([0-9]*:\)\?\(.*\)$,\2,p')"
DEB_VER="$(echo ${VERSION} | sed 's,\-[0-9a-z\~\.]*,,')"
UP_VER="$(echo ${DEB_VER} | sed 's,\~,\-,g')"
UP_VER_TAG="hostap_$(echo $UP_VER | sed -e 's,\.,_,g' -e 's,\-,_,g')"

# write to ../tarballs/, if it exists - ../ otherwise
if [ -d "${CURDIR}/../tarballs" ]; then
	ORIG_TARBALL="${CURDIR}/../tarballs/wpa_${DEB_VER}.orig.tar.gz"
else
	ORIG_TARBALL="${CURDIR}/../wpa_${DEB_VER}.orig.tar.gz"
fi

# don't overwrite existing tarballs
if [ -e "${ORIG_TARBALL}" ]; then
	echo "ERROR: don't overwrite existing ${ORIG_TARBALL}" >&2
	exit 2
fi

TEMP_SOURCE="$(mktemp -d --tmpdir wpa-orig-source.XXXXXXXXXX)"
if [ "$?" -ne 0 ] || [ -z "${TEMP_SOURCE}" ] || [ ! -d "${TEMP_SOURCE}" ]; then
	echo "ERROR: failed to create temporary working directory" >&2
	exit 3
fi

# clone upstream git repository
git clone git://w1.fi/srv/git/hostap.git "${TEMP_SOURCE}"
if [ "$?" -ne 0 ] || [ ! -d "${TEMP_SOURCE}" ]; then
	echo "ERROR: cloning git://w1.fi/srv/git/hostap-1.git failed" >&2
	rm -rf "${TEMP_SOURCE}"
	exit 4
fi

# create new usptream tarball
cd "${TEMP_SOURCE}" && \
	git archive \
		--format=tar \
		--prefix="wpa-${UP_VER}/" \
		"${UP_VER_TAG}" \
			README COPYING patches src wpa_supplicant hostapd | \
				gzip -c9 > "${ORIG_TARBALL}"
if [ "$?" -ne 0 ] || [ ! -e "${ORIG_TARBALL}" ]; then
	echo "ERROR: failure to create ${ORIG_TARBALL}" >&2
	rm -rf "${TEMP_SOURCE}"
	exit 5
else
	echo "SUCCESS: New upstream tarball has been saved at ${ORIG_TARBALL}"
	rm -rf "${TEMP_SOURCE}"
	exit 0
fi

