#!/bin/sh

set -e

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

PACKAGE="$1"
BASE="$PWD"

if [ -d "$BEN_REBUILD_CACHE" ]; then
    cd "$BEN_REBUILD_CACHE"
    CHANGES="$(find . -name "$PACKAGE"'_*.changes')"
    LOG_LINK="$(find . -name "$PACKAGE"'_*amd64.build')"
    if [ -L "$LOG_LINK" ]; then
        LOG="$(readlink "$LOG_LINK")"
        if [ -f "$LOG" ]; then
            dcmd cp -P "$LOG_LINK" "$LOG" "$BASE/build"
        fi
        if [ -f "$CHANGES" ] && [ "$(dcmd "$CHANGES" | grep '\.deb$' | wc -l)" -ge 1 ]; then
            dcmd cp "$CHANGES" "$BASE/build"
            exit 0
        else
            exit 1
        fi
    fi
fi

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