#!/usr/bin/env bash

# SPDX-License-Identifier: MIT

set -euo pipefail

plugin=$1
configurator=$2
test_root=$(mktemp -d)
trap 'rm -rf -- "$test_root"' EXIT

install -Dpm 0644 "$plugin" \
    "$test_root/usr/lib64/libinput/plugins/90-touchpad-hold-tap.lua"

TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" set \
    --minimum-anchor-age-ms 125 \
    --minimum-pause-ms 175 \
    --minimum-tap-ms 15 \
    --maximum-tap-ms 225 \
    --output-event KEY_F13

config="$test_root/etc/touchpad-hold-tap.conf"
override="$test_root/etc/libinput/plugins/90-touchpad-hold-tap.lua"
grep -qx 'MINIMUM_PAUSE_MS=175' "$config"
grep -qx 'MINIMUM_ANCHOR_AGE_MS=125' "$config"
grep -qx 'MINIMUM_TAP_MS=15' "$config"
grep -qx 'MAXIMUM_TAP_MS=225' "$config"
grep -qx 'OUTPUT_EVENT=KEY_F13' "$config"
grep -q 'minimum_pause_ms = 175' "$override"
grep -q 'minimum_anchor_age_ms = 125' "$override"
grep -q 'minimum_tap_ms = 15' "$override"
grep -q 'maximum_tap_ms = 225' "$override"
grep -q 'output_event = "KEY_F13"' "$override"

# Decimal input must neither be parsed as octal nor overflow Bash arithmetic.
TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" set --minimum-tap-ms 008
grep -qx 'MINIMUM_TAP_MS=8' "$config"
before_config=$(sha256sum "$config")
before_override=$(sha256sum "$override")
for invalid in 2001 18446744073709551616 -1 nope; do
    if TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" set --minimum-tap-ms "$invalid"; then
        exit 1
    fi
    [[ $(sha256sum "$config") == "$before_config" ]]
    [[ $(sha256sum "$override") == "$before_override" ]]
done

# Invalid template leaves both installed files unchanged and no staging clutter.
printf '%s\n' 'invalid template' > "$test_root/usr/lib64/libinput/plugins/90-touchpad-hold-tap.lua"
if TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" set --minimum-pause-ms 150; then
    exit 1
fi
[[ $(sha256sum "$config") == "$before_config" ]]
[[ $(sha256sum "$override") == "$before_override" ]]
[[ $(find "$test_root/etc" -type f | wc -l) == 2 ]]

printf 'MINIMUM_TAP_MS=12' > "$config"
TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" show | grep -qx 'MINIMUM_TAP_MS=12'

TOUCHPAD_HOLD_TAP_TEST_ROOT=$test_root bash "$configurator" reset
[[ ! -e $config ]]
[[ ! -e $override ]]

printf 'touchpad configurator tests passed\n'
