#!/bin/sh
set -e

PACKAGE=$(dpkg-parsechangelog -S Source)
VERSION=""

while [ $# -gt 0 ]; do
    case "$1" in
        --upstream-version)
            VERSION="$2"
            shift 2
            ;;
        *)
            shift
            ;;
    esac
done

if [ -z "$VERSION" ]; then
    VERSION=$(dpkg-parsechangelog -S Version | sed 's/-[^-]*$//')
fi

DIRNAME="${PACKAGE}-${VERSION}"
TARBALL="../${PACKAGE}_${VERSION}.orig.tar.gz"
# uscan's own git fetch (mode=git) already produced this raw tarball and
# symlinked $TARBALL to it; it becomes an orphan once we overwrite
# $TARBALL below with a tree that includes submodules.
RAWTARBALL="../${PACKAGE}-${VERSION}.tar.gz"

echo "Cloning ${PACKAGE} (version ${VERSION}) with submodules..."

BUILDDIR=$(mktemp -d)
trap 'rm -rf "$BUILDDIR"' EXIT

git clone --depth 1 --recursive https://github.com/raspberrypi/usbboot.git "$BUILDDIR/$DIRNAME"

# $TARBALL is currently a symlink to $RAWTARBALL (created by uscan's git
# fetch). Remove it first, otherwise tar follows the symlink and writes into
# $RAWTARBALL, which the rm below then deletes -- leaving a dangling symlink.
rm -f "$TARBALL"

tar -czf "$TARBALL" -C "$BUILDDIR" --exclude-vcs "$DIRNAME"

rm -f "$RAWTARBALL"

echo "Created $TARBALL"
