#!/bin/zsh -euf

# Remove from reprepro (must be configured, maybe via env) the .deb files
# which are provided by the given .changes file.
# Based on the source pkg name!

usage()
{
    setopt POSIX_ARGZERO
    cat <<EOF
usage: ${0##*/} [+-h] [--] {distribution} {CHANGES-file}
EOF
    unsetopt POSIX_ARGZERO
}

while getopts :h OPT; do
    case $OPT in
        h|+h)
            usage
            exit 0
            ;;
        *)
            usage
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1


if [ $# -lt 2 ]; then
    usage
    exit 1
fi

distribution=$1
CHANGES_FILE=$2

source=($(sed --quiet -e '/^Source:/{s/Source: //;p}' $CHANGES_FILE))

if false;
then
    packages=($(sed --quiet -e '/^Binary:/{s/Binary://;p}' $CHANGES_FILE))
    foreach package ($packages) {
        reprepro remove $distribution $package
    }
else
    # remove by source pkg name:
    # if DEBUG reprepro listfilter UNRELEASED '$Source (==apt)'
    reprepro removefilter $distribution "\$Source (==$source)"

    # --export=never
    # but: if you do not want some of the files pointed to by the untouched index files to vanish.
fi


dirs=(pool dists)
(
    cd $REPREPRO_BASE_DIR
    if ! git diff --exit-code -- $dirs &> /dev/null;
    then
        git add $dirs
        git commit -m "drop old $source"
    fi
)
# --export=never
