#!/bin/sh

set -e

ARCH=amd64
BASE=$1
SUFFIX=$2
PACKAGE=$3
INTERACTIVE=$4
OCAML_VERSION=${BASE##*-}

su -c "mkdir /tmp/build" builder
cd /tmp/build
DSC=$BASE/override/${PACKAGE}_*.dsc
if ! [ -f $DSC ]; then
    su -c "apt-get -o 'APT::Get::Only-Source=true' source -d $PACKAGE" builder
    DSC=*.dsc
fi
su -c "dpkg-source -x $DSC" builder
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
su -c "cp ../new-changelog debian/changelog" builder
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 su -c "dpkg-buildpackage -us -uc -sa" builder; then
    dcmd cp ../*.changes $BASE/build/
else
    R=$?
    if [ -n "$INTERACTIVE" ]; then
        bash -i
    fi
    exit $R
fi
