#!/bin/sh

set -e

ARCH=amd64
BASE=$1
SUFFIX=$2
PACKAGE=$3
INTERACTIVE=$4
OCAML_VERSION=${BASE##*-}
RUNUSER="runuser -u builder --"

$RUNUSER mkdir /tmp/build
cd /tmp/build
DSC=$BASE/override/${PACKAGE}_*.dsc
if ! [ -f $DSC ]; then
    $RUNUSER apt-get -o 'APT::Get::Only-Source=true' source -d $PACKAGE
    DSC=*.dsc
fi
$RUNUSER dpkg-source -x $DSC
cd $PACKAGE-*
VERSION=$(dpkg-parsechangelog -S Version)

cat > ../new-entry <<EOF
$PACKAGE ($VERSION$SUFFIX) unstable-ocaml; urgency=medium

  * Recompile with OCaml $OCAML_VERSION

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

EOF

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

/usr/lib/pbuilder/pbuilder-satisfydepends

if command -v ocamlc > /dev/null; then
    if [ "$(ocamlc -version)" != "$OCAML_VERSION" ]; then
        echo "Wrong OCaml version: $(ocamlc -version)"
        exit 1
    fi
fi

if $RUNUSER dpkg-buildpackage -us -uc -sa; then
    dcmd cp ../*.changes $BASE/build/
else
    R=$?
    if [ -n "$INTERACTIVE" ]; then
        bash -i
    fi
    exit $R
fi
