#!/bin/bash

set -e
set -o pipefail

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

PACKAGE=$1
BASE=$PWD
VERSION=${BASE##*-}

if ! [ -f build/ocaml-$VERSION.tgz ]; then
    echo "build/ocaml-$VERSION.tgz is missing!"
    exit 1
fi

if [ "$USER" != "root" ]; then
    echo "Must be run as root!"
    exit 1
fi

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

$TIMELIMIT /usr/bin/time pbuilder execute --basetgz build/ocaml-$VERSION.tgz --bindmounts "$BASE" -- usr/lib/pbuilder-rebuild.sh $BASE +o1 $PACKAGE $INTERACTIVE 2>&1 | tee build/$PACKAGE.log
