#!/usr/bin/env bash
# Shared companions: scripts/ci/verify-file-checksum.sh scripts/ci/fixture-lifecycle.sh
set -euo pipefail
root="$0"
[[ "$root" == /* ]] || root="$PWD/$root"
root="$(cd -P "${root%/*}/../.." && printf '%s/.' "$PWD")"
root="${root%/.}"
# shellcheck source=scripts/ci/fixture-lifecycle.sh
source "$root/scripts/ci/fixture-lifecycle.sh"
fixture="$(fixture_create "${TMPDIR:-/tmp}/file-digests.XXXXXX")"
fixture_complete=false
finish() {
    local status=$?
    chmod u+r "$fixture/unreadable" 2>/dev/null || true
    fixture_finish "$status" "$fixture" 'Digest fixtures retained'
}
trap finish EXIT
checker="$root/scripts/ci/verify-file-checksum.sh"
# macOS bootstrap uses system Bash 3.2 even when PATH selects a newer Bash.
# Parse with that interpreter before exercising the selected shell below.
/bin/bash -n "$checker"
sha256=ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
sha512=ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
cd "$fixture"
for file in 'file with spaces' '-leading-dash' 'back\slash' $'line\nbreak'; do printf abc > "$file"; done
for backend in gnu perl; do
    mkdir "$backend"
    if [[ "$backend" == gnu ]]; then
        if ! command -v sha256sum >/dev/null || ! command -v sha512sum >/dev/null; then
            echo 'GNU backend unavailable on this host; native shasum is tested instead'
            continue
        fi
        for tool in sha256sum sha512sum; do ln -s "$(command -v "$tool")" "$backend/$tool"; done
    else
        ln -s "$(command -v shasum)" "$backend/shasum"
    fi
    for algorithm in sha256 sha512; do
        expected="${!algorithm}"
        for file in 'file with spaces' '-leading-dash' 'back\slash' $'line\nbreak'; do
            actual="$(PATH="$fixture/$backend" "$BASH" "$checker" --print "$algorithm" "$file")"
            [[ "$actual" == "$expected" ]] || exit 1
            PATH="$fixture/$backend" "$BASH" "$checker" "$algorithm" "$expected" "$file"
        done
    done
done
expect_failure() {
    local status=0
    "$@" > "$fixture/output" 2> "$fixture/error" || status=$?
    [[ "$status" != 0 && ! -s "$fixture/output" && -s "$fixture/error" ]] || exit 1
}
expect_failure "$BASH" "$checker" --print sha256 absent
expect_failure "$BASH" "$checker" --print sha256 "$fixture"
expect_failure "$BASH" "$checker" --print md5 'file with spaces'
expect_failure "$BASH" "$checker" sha256 invalid 'file with spaces'
expect_failure "$BASH" "$checker" sha256 "${sha256/ba/aa}" 'file with spaces'
expect_failure "$BASH" "$checker"
printf abc > unreadable
chmod 000 unreadable
if [[ ! -r unreadable ]]; then expect_failure "$BASH" "$checker" --print sha256 unreadable; fi
mkdir empty
expect_failure env PATH="$fixture/empty" "$BASH" "$checker" --print sha256 'file with spaces'
mkdir fake
# Selected backend failures must never be hidden by a successful fallback.
printf '#!%s\nprintf "unexpected fallback" >&2\nexit 99\n' "$BASH" > fake/shasum
# shellcheck disable=SC2016 # Variables are expanded by the generated backend.
printf '#!%s\nprintf "%%s" "$DIGEST_OUTPUT"\nexit "$DIGEST_STATUS"\n' "$BASH" > fake/sha256sum
chmod +x fake/*
for output in '' abc "$sha256 extra" "$sha256  - extra" "$sha512  -" "$sha256  -"$'\n'"$sha256  -"; do
    expect_failure env PATH="$fixture/fake" DIGEST_OUTPUT="$output" DIGEST_STATUS=0 \
        "$BASH" "$checker" --print sha256 'file with spaces'
done
status=0
env PATH="$fixture/fake" DIGEST_OUTPUT="$sha256  -" DIGEST_STATUS=9 \
    "$BASH" "$checker" --print sha256 'file with spaces' > "$fixture/output" 2> "$fixture/error" || status=$?
[[ "$status" == 9 && ! -s "$fixture/output" && -s "$fixture/error" ]] || exit 1
[[ "$(cat "$fixture/error")" != *'unexpected fallback'* ]] || exit 1
status=0
env PATH="$fixture/fake" DIGEST_OUTPUT="$sha256  -" DIGEST_STATUS=3 \
    "$BASH" "$checker" --print sha256 'file with spaces' > "$fixture/output" 2> "$fixture/error" || status=$?
[[ "$status" == 3 && ! -s "$fixture/output" && "$(cat "$fixture/error")" == *'backend failed'* ]] || exit 1
[[ "$(cat "$fixture/error")" != *'NUL byte'* ]] || exit 1
# NUL must not disappear from an otherwise valid digest/record. Exercise both
# algorithms and the Perl selection without relying on a host's GNU binaries.
for backend in sha256sum sha512sum shasum; do
    mkdir "nul-$backend"
    printf '#!%s\n' "$BASH" > "nul-$backend/$backend"
    cat >> "nul-$backend/$backend" <<'SCRIPT'
printf '%s\0%s' "$DIGEST_BEFORE" "$DIGEST_AFTER"
SCRIPT
    chmod +x "nul-$backend/$backend"
    algorithm=sha256
    [[ "$backend" != sha512sum ]] || algorithm=sha512
    expected="${!algorithm}"
    for position in leading digest marker trailing; do
        case "$position" in
            leading) before=''; after="$expected  -" ;;
            digest) before="${expected:0:12}"; after="${expected:12}  -" ;;
            marker) before="$expected "; after=' -' ;;
            trailing) before="$expected  -"; after='' ;;
        esac
        for mode in print verify; do
            arguments=("$algorithm" "$expected" 'file with spaces')
            [[ "$mode" != print ]] || arguments=(--print "$algorithm" 'file with spaces')
            expect_failure env PATH="$fixture/nul-$backend" DIGEST_BEFORE="$before" DIGEST_AFTER="$after" \
                "$BASH" "$checker" "${arguments[@]}"
            # Rejected output is reported once; the backend itself did not fail.
            [[ "$(cat "$fixture/error")" == *'contains a NUL byte'* ]] || exit 1
            [[ "$(cat "$fixture/error")" != *'backend failed'* ]] || exit 1
        done
    done
done
echo 'Portable digest vectors, filenames, backend failures and verifier round trips passed'
fixture_complete=true
