#!/usr/bin/bash

set -euo pipefail

controller=$1
payload_config=$2

bash -n "$controller"
"$controller" --help | grep -q '^  .* enable \[--rpm PATH\] \[--force\] \[--yes\]$'

reject() {
    if "$controller" "$@" >/dev/null 2>&1; then
        printf 'Invalid invocation unexpectedly succeeded: %s\n' "$*" >&2
        exit 1
    fi
}

reject
reject unknown-command
reject status --yes
reject enable --rpm
reject enable --unknown
reject disable --force

payload_url=
payload_sha256=
# shellcheck source=/dev/null
source "$payload_config"
[[ $payload_url == https://*/*.rpm ]]
[[ $payload_sha256 =~ ^[[:xdigit:]]{64}$ ]]

# Load the functions through the harmless help command, then replace DNF with
# a test function. Never invoke the package manager in this test.
(
    source "$controller" --help >/dev/null
    dnf5() {
        [[ $(umask) == 0022 && $1 == test-argument ]]
    }
    umask 077
    run_dnf test-argument
    [[ $(umask) == 0077 ]]
    dnf5() { return 23; }
    if run_dnf test-argument; then
        printf 'DNF failure was not propagated.\n' >&2
        exit 1
    else
        [[ $? == 23 ]]
    fi
)

printf 'Controller tests passed.\n'
