#!/bin/sh
# dur-allow: let single packages through from the DUR's components that
# are off (/etc/apt/preferences.d/dur, package dur-archive), the way
# backports are used, but for the named package only.  Its dependencies
# from components that are off need allowing too: apt names them.
#   dur-allow                 list the allowed packages
#   dur-allow <package>...    allow them
#   dur-allow -r <package>... take them back (apt keeps them installed)
set -eu

file=/etc/apt/preferences.d/dur-allow

list() {
    [ -r "$file" ] && sed -n 's/^Package: //p' "$file" || true
}

case ${1:-} in
"")
    list
    exit 0
    ;;
-h|--help)
    sed -n '2,8s/^# \{0,1\}//p' "$0"
    exit 0
    ;;
esac
[ "$(id -u)" = 0 ] || { echo "dur-allow: run as root" >&2; exit 1; }

remove=
if [ "$1" = -r ]; then
    remove=1
    shift
fi
for package in "$@"; do
    case $package in
    *[!a-z0-9+.-]*|[!a-z0-9]*)
        echo "dur-allow: not a package name: $package" >&2
        exit 1
        ;;
    esac
done

tmp=$(mktemp "$file.XXXXXX")
trap 'rm -f "$tmp"' EXIT
{
    echo "# dur-allow: packages from the DUR's components that are off"
    { list; [ -n "$remove" ] || printf '%s\n' "$@"; } | sort -u |
    while read -r package; do
        if [ -n "$remove" ]; then
            for p in "$@"; do
                [ "$p" = "$package" ] && continue 2
            done
        fi
        printf '\nPackage: %s\nPin: release o=DUR\nPin-Priority: 100\n' "$package"
    done
} > "$tmp"
chmod 644 "$tmp"
mv "$tmp" "$file"
trap - EXIT
