#!/bin/sh
# Verify that the ssh-env shell integration feature is enabled by default
# and that shell-integration-features directives in the config file are
# honoured.
set -eu

OUT=/tmp/out.txt
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR" $OUT' EXIT

# Launch ghostty under Xvfb with an isolated XDG_CONFIG_HOME and record
# GHOSTTY_SHELL_FEATURES in $OUT.
run_ghostty() {
    rm -f "$OUT"
    XDG_CONFIG_HOME="$1" xvfb-run -a ghostty -e sh -c "echo \$GHOSTTY_SHELL_FEATURES > $OUT"
    test -f "$OUT"
    echo "GHOSTTY_SHELL_FEATURES: $(cat "$OUT")"
}

assert_present() {
    if ! grep -q "$1" "$OUT"; then
        echo "FAIL: expected '$1' in GHOSTTY_SHELL_FEATURES" >&2
        exit 1
    fi
}

assert_absent() {
    if grep -q "$1" "$OUT"; then
        echo "FAIL: unexpected '$1' in GHOSTTY_SHELL_FEATURES" >&2
        exit 1
    fi
}

# Sub-test 1: no config file. ssh-env must be enabled by default.
echo "Sub-test 1: no config file"
mkdir -p "$WORKDIR/sub1"
run_ghostty "$WORKDIR/sub1"
assert_present "ssh-env"
echo "Sub-test 1: PASS"

# Sub-test 2: shell-integration-features=no-cursor. ssh-env must remain
# enabled, cursor:blink must be gone.
echo "Sub-test 2: shell-integration-features=no-cursor"
mkdir -p "$WORKDIR/sub2/ghostty"
echo "shell-integration-features=no-cursor" > "$WORKDIR/sub2/ghostty/config"
run_ghostty "$WORKDIR/sub2"
assert_present "ssh-env"
assert_absent "cursor:blink"
echo "Sub-test 2: PASS"

# Sub-test 3: shell-integration-features=no-cursor,no-ssh-env. Both
# cursor:blink and ssh-env must be gone.
echo "Sub-test 3: shell-integration-features=no-cursor,no-ssh-env"
mkdir -p "$WORKDIR/sub3/ghostty"
echo "shell-integration-features=no-cursor,no-ssh-env" > "$WORKDIR/sub3/ghostty/config"
run_ghostty "$WORKDIR/sub3"
assert_absent "cursor:blink"
assert_absent "ssh-env"
echo "Sub-test 3: PASS"

echo "All sub-tests passed"
