#!/usr/bin/env bash

# With fnox's daemon enabled, the first interactive `mise run` resolves on the terminal through
# the fnox CLI (which stores into the daemon) and the second reads the daemon's cache with no
# fnox resolve at all. mise never starts the daemon itself.
FNOX_VERSION=1.39.0 # the first fnox with `fnox env --json` and daemon protocol 6

if ! script -qec true /dev/null >/dev/null 2>&1; then
  echo "Skipping: util-linux script is not available"
  exit 0
fi
if ! mise ls-remote fnox | grep -qx "$FNOX_VERSION"; then
  echo "Skipping: fnox $FNOX_VERSION (the first fnox with daemon protocol 6) is not listed by mise ls-remote"
  exit 0
fi

# Installed without declaring it in the project: the project's own tools win over PATH, which
# would bypass the logging wrapper.
mise install "fnox@$FNOX_VERSION"
FNOX_REAL="$(mise which fnox --tool "fnox@$FNOX_VERSION")"
[[ -x $FNOX_REAL ]] || fail "fnox $FNOX_VERSION has no executable at $FNOX_REAL"
mkdir -p "$HOME/bin"
cat >"$HOME/bin/fnox" <<WRAP
#!/usr/bin/env bash
printf '%s\n' "\$*" >>"$PWD/fnox-calls.log"
exec "$FNOX_REAL" "\$@"
WRAP
chmod +x "$HOME/bin/fnox"
export PATH="$HOME/bin:$PATH"

# Unix socket paths are short: keep the runtime dir directly under the harness-owned HOME
export XDG_RUNTIME_DIR="$HOME/run"
mkdir -m 0700 "$XDG_RUNTIME_DIR"

cat >fnox.toml <<'TOML'
root = true

[daemon]
enabled = true
idle_timeout = "2m"

[providers.plain]
type = "plain"

[secrets]
DEPLOY_KEY = { provider = "plain", value = "deploy-s3cr3t-0001", env = "exec" }
TOML
trap 'fnox daemon stop >/dev/null 2>&1 || true' EXIT
cat >mise.toml <<'TOML'
[secrets.fnox]

[tasks.deploy]
secrets = ["DEPLOY_KEY"]
run = 'printf %s "$DEPLOY_KEY" >deploy.out'
TOML

tty() { script -qec "env -u CI -u GITHUB_ACTIONS MISE_DEBUG=1 mise run deploy" /dev/null; }

# first run: the CLI resolves on the terminal and fills the daemon
tty >first.out 2>&1
assert "cat deploy.out" "deploy-s3cr3t-0001"
assert_not_contains "cat first.out" "fnox daemon hit"
assert "grep -c -- '--describe' fnox-calls.log" "1"
assert "grep -- 'env --json' fnox-calls.log | grep -v -c -- '--describe'" "1"
assert_not_contains "grep -- 'env --json' fnox-calls.log | grep -v -- '--describe'" "--no-daemon"

# second run: a daemon hit, so only the describe call reaches fnox
rm -f fnox-calls.log deploy.out
tty >second.out 2>&1
assert "cat deploy.out" "deploy-s3cr3t-0001"
assert_contains "cat second.out" "fnox daemon hit"
assert "grep -c -- '--describe' fnox-calls.log" "1"
assert "grep -v -c -- '--describe' fnox-calls.log || true" "0"

# `mise secrets ls` reports the daemon, and never starts one
assert_contains "mise secrets ls 2>&1" "daemon: running (protocol 6)"
fnox daemon stop
assert_contains "mise secrets ls 2>&1" "daemon: not running"
