#!/bin/sh

set -e

PACKAGE=$1

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

has_debs () {
    [ -f "$1" ] && [ "$(dcmd --deb "$1" | wc -l)" -ge 1 ]
}

reached_timelimit () {
    log="$(find "$BEN_REBUILD_TIME_REFERENCE"/$1 -name '*.build' | grep -v 'Z.build$' | tail -n1)"
    if [ -f "$log" ]; then
        a="$(grep -E '^(DEB_BUILD_OPTIONS=|Build-Time: )' "$log" | uniq)"
        p="$(echo "$a" | sed -nr 's/^.*parallel=([0-9]+).*$/\1/p')"
        t="$(echo "$a" | sed -nr 's/^Build-Time: ([0-9]+).*$/\1/p')"
        if [ -z "$p" ]; then p=1; fi
        if [ -z "$t" ]; then t=0; fi
        [ "$(($p * $t))" -gt "$BEN_REBUILD_TIMELIMIT" ]
    else
        false
    fi
}

if has_debs repo/pool/$PACKAGE/*.changes; then
    # The package exists in the new universe, report success
    exit 0
elif [ "$(find repo/pool/$PACKAGE -name "*.build" | wc -l)" -ge 1 ]; then
    # A log already exists, do not retry to build
    exit 2
elif [ -f repo/pool/$PACKAGE/reason.txt ]; then
    # The package fails for a known reason, report failure
    exit 2
elif [ -f "$BEN_REBUILD_FTBFS" ] && grep -q "^$PACKAGE " "$BEN_REBUILD_FTBFS"; then
    # The package FTBFS, report failure
    mkdir -p repo/pool/$PACKAGE
    grep "^$PACKAGE " "$BEN_REBUILD_FTBFS" | tail -n1 \
        | { read a b c; echo "# FTBFS (#$b) (pink)" > repo/pool/$PACKAGE/reason.txt; }
    exit 2
elif [ -n "$BEN_REBUILD_TIMELIMIT" ] && reached_timelimit $PACKAGE; then
    # The package took too much time to build in the past, report failure
    mkdir -p repo/pool/$PACKAGE
    echo '# took too much time in the past (orange)' > repo/pool/$PACKAGE/reason.txt
    exit 2
elif [ -f repo/pool/$PACKAGE/fake ]; then
    # Assume the package exists in the new universe, report success
    exit 0
fi

# Package status unknown, try to build it
exit 1
