#!/bin/bash

set -e

if ! git rev-parse --git-dir >/dev/null; then
    echo "Not in a git repo; please run from a clone of" >&2
    echo "https://github.com/raspberrypi/usbboot" >&2
    exit 1
fi
if [ -z "$DEB_SOURCE" -o -z "$DEB_VERSION" -o -z "$DEB_VERSION_UPSTREAM" ]; then
    echo "Expected to find DEB_SOURCE, DEB_VERSION, and DEB_VERSION_UPSTREAM " >&2
    echo "in my env. Please run me via debian/rules" >&2
    exit 1
fi

BASE_REV=pios/trixie
MERGE_BASE=$(git merge-base HEAD "$BASE_REV")
DEB_VERSION_UPSTREAM="${DEB_VERSION_UPSTREAM%%+nowin}"
OUTPUT_FILE="${DEB_SOURCE}_${DEB_VERSION_UPSTREAM}.tar.gz"

echo "BASE_REV=${BASE_REV}" >&2
echo "MERGE_BASE=${MERGE_BASE}" >&2
echo "DEB_VERSION_UPSTREAM=${DEB_VERSION_UPSTREAM}" >&2
echo "OUTPUT_FILE=${OUTPUT_FILE}" >&2

if ! echo "$DEB_VERSION" | grep -q "ubuntu"; then
    echo "The package version contains no \"ubuntu\" component" >&2
    exit 1
elif echo "$DEB_VERSION_UPSTREAM" | grep -q "+git"; then
    MERGE_BASE_PREFIX="${MERGE_BASE:0:7}"
    UPSTREAM_SUFFIX="${DEB_VERSION_UPSTREAM: -7:7}"
    if [ "$MERGE_BASE_PREFIX" != "$UPSTREAM_SUFFIX" ]; then
        echo "The deb version suffix doesn't appear to match the common base" >&2
        echo "of the packaging branch and master" >&2
        exit 1
    fi
else
    MERGE_BASE_VERSION=$(
        git cat-file -p \
            $(git ls-tree "$MERGE_BASE" debian/changelog | awk '{print $3}') \
        | dpkg-parsechangelog -l - \
        | grep "^Version:" \
        | awk '{print $2}'
    )
    if [ "$MERGE_BASE_VERSION" != "$DEB_VERSION_UPSTREAM" ]; then
        echo "The package version prefix does not match the version at the " >&2
        echo "common base of the packaging branch and master" >&2
        exit 1
    fi
fi

git archive \
    --prefix usbboot/ \
    --output ../"$OUTPUT_FILE" \
    "$MERGE_BASE"
mk-origtargz --compression gzip ../"$OUTPUT_FILE"
