#!/usr/bin/env bash

# SPDX-License-Identifier: MIT

set -euo pipefail

if (( $# != 3 )); then
    printf 'Usage: %s SCRIPT PATCH FIXTURE\n' "${0##*/}" >&2
    exit 2
fi

script=$1
patch_file=$2
fixture=$3
tmpdir=$(mktemp -d)
trap 'rm -rf -- "$tmpdir"' EXIT

root="$tmpdir/root"
target_dir="$root/usr/share/plasma/shells/org.kde.plasma.desktop/contents/lockscreen"
target="$target_dir/LockScreenUi.qml"
mkdir -p "$target_dir"
cp "$fixture" "$target"

run_tool() {
    PLASMA_ALWAYS_SHOW_UNLOCK_ROOT="$root" \
    PLASMA_ALWAYS_SHOW_UNLOCK_PATCH="$patch_file" \
        bash "$script" "$@"
}

if run_tool status >/dev/null 2>&1; then
    printf 'Expected an unpatched fixture.\n' >&2
    exit 1
fi

run_tool apply >/dev/null
run_tool status >/dev/null
grep -q 'function onViewVisibleChanged()' "$target"
grep -q 'id: resumeAuthenticationTimer' "$target"
grep -q 'id: postGraceAuthenticationTimer' "$target"
grep -q 'interval: 1500' "$target"
grep -q 'interval: 6000' "$target"
grep -q 'running: root.viewVisible' "$target"
grep -q 'onTriggered: authenticator.startAuthenticating()' "$target"
grep -q 'function onResumingFromSuspend()' "$target"
[[ $(grep -c 'resumeAuthenticationTimer.restart()' "$target") -eq 1 ]]
grep -q 'cursorShape: Qt.ArrowCursor' "$target"
grep -q 'state: "on"' "$target"
grep -q 'opacity: 0' "$target"
grep -q 'lockScreenUiVisible: true' "$target"
grep -q 'lockScreenRoot.uiVisible = false' "$target"
if grep -q 'seenPositionChange\|running: parent.uiVisible\|repeat: true' "$target"; then
    printf 'The patched fixture still contains prompt-hiding logic.\n' >&2
    exit 1
fi

patched_checksum=$(sha256sum "$target")
run_tool apply >/dev/null
[[ $(sha256sum "$target") == "$patched_checksum" ]]

run_tool revert >/dev/null
cmp "$fixture" "$target"
run_tool revert >/dev/null
cmp "$fixture" "$target"

sed -i 's/property bool seenPositionChange: false/property bool unexpectedState: false/' "$target"
unsupported_checksum=$(sha256sum "$target")
if run_tool apply >/dev/null 2>&1; then
    printf 'Expected an unsupported modified fixture to be rejected.\n' >&2
    exit 1
fi
[[ $(sha256sum "$target") == "$unsupported_checksum" ]]
if run_tool revert >/dev/null 2>&1; then
    printf 'Expected an unsupported modified fixture to be rejected on revert.\n' >&2
    exit 1
fi
[[ $(sha256sum "$target") == "$unsupported_checksum" ]]
status=0
run_tool status >/dev/null 2>&1 || status=$?
[[ $status -eq 2 ]]

rm -- "$target"
if run_tool apply >/dev/null 2>&1; then
    printf 'Expected a missing lock screen to be rejected.\n' >&2
    exit 1
fi
[[ ! -e $target ]]

printf 'plasma-always-show-unlock tests passed\n'
