#!/bin/bash

set -e

if [ -d ../build ]; then
    cd ..
fi

. ben/env.sh

PACKAGE="$1"
shift
BASE="$PWD"
TARBALL="ben/rootfs.tar.zst"

if ! [ -f "$TARBALL" ]; then
    echo "$TARBALL is missing!"
    exit 1
fi

if [ -n "$BEN_REBUILD_TIMELIMIT" ]; then
    TIMELIMIT="timelimit -t $BEN_REBUILD_TIMELIMIT"
else
    TIMELIMIT=
fi

SRCDIR="$(mktemp --tmpdir --directory tmp.ben.transition-scripts.XXXXXXXXXX)"
trap "rm -rf $SRCDIR" EXIT

cd "$SRCDIR"
if [ -d "$BASE/override" ]; then
    OVERRIDE="$(find "$BASE/override" -name "${PACKAGE}_*.dsc")"
fi
if [ -n "$OVERRIDE" ]; then
    if [ -f "$OVERRIDE" ]; then
        echo "Using $OVERRIDE..."
        dpkg-source -x "$OVERRIDE"
    else
        echo "Problem with override:"
        echo "$OVERRIDE"
        exit 1
    fi
else
    PKG_STANZA="$(ben query -s Directory,Files '.package ~ "'"$PACKAGE"'"' $BASE/ben/Sources)"
    if [ "$(echo "$PKG_STANZA" | grep '^Directory: ' | wc -l)" -ge 1 ]; then
        PKG_DIR="$(echo "$PKG_STANZA" | grep '^Directory: ' | tail -n 1 | { read a b; echo $b; })"
        PKG_FILE="$(echo "$PKG_STANZA" | grep '\.dsc$' | tail -n 1 | { read a b c; echo $c; })"
        URL="$MIRROR/$PKG_DIR/$PKG_FILE"
        echo "Using $URL..."
        dget -x "$URL"
    else
        echo "Not exactly one package found in Sources:"
        echo "$PKG_STANZA"
        exit 1
    fi
fi

cd $PACKAGE-*
PKG_VERSION=$(dpkg-parsechangelog -S Version)
cat > ../new-entry <<EOF
$PACKAGE ($PKG_VERSION$SUFFIX) $SUITE; urgency=medium

  * Rebuild for transition $NAME

 -- Anonymous Builder <builder@example.org>  $(date -R)

EOF
cat ../new-entry debian/changelog > ../new-changelog
cp ../new-changelog debian/changelog
rm -f ../new-entry ../new-changelog

SBUILD_CONFIG="$BASE/ben/sbuild.conf" $TIMELIMIT sbuild --build-dir="$BASE/build" --no-clean-source --source --force-orig-source "$@"
