#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
set -euo pipefail

if (( $# != 4 )); then
    printf 'Usage: %s SCRIPT LEGACY_PATCH VISIBILITY_PATCH FIXTURE\n' "${0##*/}" >&2
    exit 2
fi
script=$1
legacy_patch=$2
visibility_patch=$3
fixture=$4
tmpdir=$(mktemp -d)
trap 'rm -rf -- "$tmpdir"' EXIT
target_dir="$tmpdir/usr/share/plasma/shells/org.kde.plasma.desktop/contents/lockscreen"
target="$target_dir/LockScreenUi.qml"
mkdir -p "$target_dir"
cp "$fixture" "$target"
chmod 644 "$target"

run_tool() {
    PLASMA_ALWAYS_SHOW_UNLOCK_ROOT="$tmpdir" \
    PLASMA_ALWAYS_SHOW_UNLOCK_PATCH="$legacy_patch" \
    PLASMA_ALWAYS_SHOW_UNLOCK_VISIBILITY_PATCH="$visibility_patch" \
        bash "$script" "$@"
}

run_tool apply
run_tool status
[[ $(grep -c 'FedoraToolsUnlockPrompt {' "$target") -eq 1 ]]
grep -q 'running: !authenticator.unlocked && parent.uiVisible' "$target"
! grep -q 'FedoraToolsFingerprintRetry\|resumeAuthenticationTimer' "$target"
[[ $(stat -c %a "$target") == 644 ]]
patched_checksum=$(sha256sum "$target")
run_tool apply
[[ $(sha256sum "$target") == "$patched_checksum" ]]
run_tool revert
run_tool revert
cmp "$fixture" "$target"

# Layout changes outside the small insertion point should not break upgrades.
sed -i -e 's/    id: lockScreenUi/        id: lockScreenUi/' \
    -e '/property bool blockUI/i\        // A new upstream comment.' "$target"
cp "$target" "$tmpdir/modified.qml"
run_tool apply
run_tool revert
cmp "$tmpdir/modified.qml" "$target"

for id in lockScreenRoot fadeoutTimer; do
    sed "s/id: $id/id: unsupportedObject/" "$fixture" > "$target"
    checksum=$(sha256sum "$target")
    if run_tool apply >/dev/null 2>&1; then
        printf 'Expected an unsupported interface to be rejected.\n' >&2
        exit 1
    fi
    [[ $(sha256sum "$target") == "$checksum" ]]
    status=0
    run_tool status >/dev/null 2>&1 || status=$?
    [[ $status -eq 2 ]]
done
printf 'Modern Plasma visibility patch tests passed\n'
