#!/bin/sh

set -e

PACKAGE=$1

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

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

. ben/env.sh

BASE="$PWD"

if [ -d "$BEN_REBUILD_CACHE" ]; then
    cd "$BEN_REBUILD_CACHE"
    CHANGES="$(find . -name "$PACKAGE"'_*.changes')"
    LOG_LINK="$(find . -name "$PACKAGE"'_*'"$ARCH"'.build')"
    if [ -L "$LOG_LINK" ]; then
        LOG="$(readlink "$LOG_LINK")"
        if [ -f "$LOG" ]; then
            dcmd cp -P "$LOG_LINK" "$LOG" "$BASE/build"
        fi
        if has_debs "$CHANGES"; then
            dcmd cp "$CHANGES" "$BASE/build"
            exit 0
        else
            exit 1
        fi
    fi
fi

cd "$BASE"
exec usr/bin/rebuild.sh "$PACKAGE"
