#!/bin/sh

set -e

PACKAGE=$1

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

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

if [ -f pool/$PACKAGE/fake ]; then
    if [ -f pool/$PACKAGE/reason.txt ]; then
        # The package fails for a known reason, report failure
        exit 2
    else
        # Assume the package exists in the new universe, report success
        exit 0
    fi
fi

if [ -d pool/$PACKAGE ]; then
    if has_debs pool/$PACKAGE/*.changes; then
        # The package exists in the new universe, report success
        exit 0
    elif [ "$(find pool/$PACKAGE -name "*.build" | wc -l)" -ge 1 ]; then
        # A log already exists, do not retry to build
        exit 2
    else
        # Package status unknown, try to build it
        exit 1
    fi
fi

# Package status unknown, try to build it
exit 1
