THIS_PATH=$PWD

BEN_PATH=/usr/share/doc/ben
BEN=/usr/bin/ben

# Detect if we are running from a git checkout
if [ -d $(dirname $0)/../../.git ]; then
    BEN_PATH=$(readlink -f $(dirname $0)/../..)
    BEN=$BEN_PATH/_build/install/default/bin/ben
fi

ben () {
    $BEN "$@"
}

download () {
    cd $THIS_PATH
    mkdir -p $1 && ( cd $1 && ben download -c $BEN_PATH/examples/download/$1.ben --use-cache )
}

update () {
    cd $THIS_PATH
    download testing
    download unstable
    mkdir -p new
    cd new
    echo Downloading excuses.yaml...
    curl --silent https://release.debian.org/britney/excuses.yaml > excuses.yaml
    echo Parsing excuses.yaml...
    yq '.sources | map({key:.["item-name"],value:{verdict:.["migration-policy-verdict"],excuses:.excuses}}) | from_entries' < excuses.yaml > excuses.json
    cd ..
}

migrate () {
    cd $THIS_PATH/new
    ben migrate ../testing/ben.cache ../unstable/ben.cache "$@"
    cd ..
}

get_uninstallables () {
    dose-debcheck --failures --explain $1 |
    $BEN_PATH/examples/migrate/extract-uninstallables.py
}

debcheck () {
    cd $THIS_PATH
    for u in testing/Packages_*; do
        u=${u##*/}
        echo "=====> $u <=====";
        diff -u <(get_uninstallables testing/$u) <(get_uninstallables new/$u)
        if [ $? -ne 0 ]; then return $?; fi
    done
}

debcheck_parallel () {
    cd $THIS_PATH
    THIS_JOBS=()
    for u in testing/Packages_*; do
        u=${u##*/}
        arch=${u##*_}
        diff -u <(get_uninstallables testing/$u) <(get_uninstallables new/$u) > new/debcheck_$arch &
        THIS_JOBS+=$!
    done
    wait "${THIS_JOBS[@]}"
    for u in new/debcheck_*; do
        arch=${u##*_}
        echo "=====> $arch <====="
        cat $u
    done
}
