#!/usr/bin/env bash
# Read-only shell fingerprint, plus a startup sample in a throwaway ZDOTDIR.
# Does not edit $HOME, change the login shell, or install packages.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"

echo "uname=$(uname -srm)"
echo "zsh_version=$(zsh --version)"
echo "zsh_path=$(command -v zsh)"
echo "SHELL=${SHELL-}"
echo "script_comm=$(ps -p $$ -o comm=)"
echo "ZSH_VERSION_in_zsh=$(zsh -c 'print -r -- $ZSH_VERSION')"

if sh_out=$(/bin/sh -c 'print $ZSH_VERSION' 2>&1); then
  echo "sh_print=unexpected_success"
else
  echo "sh_print_exit=$?"
  echo "sh_print_err=${sh_out}"
fi

for tool in fzf zoxide starship direnv atuin brew; do
  if command -v "$tool" >/dev/null 2>&1; then
    echo "${tool}=present"
  else
    echo "${tool}=absent"
  fi
done

antidote_file=absent
for candidate in \
  "${ZDOTDIR:-$HOME}/.antidote/antidote.zsh" \
  /opt/homebrew/opt/antidote/share/antidote/antidote.zsh \
  /usr/local/opt/antidote/share/antidote/antidote.zsh
do
  if [[ -r $candidate ]]; then
    antidote_file=$candidate
    break
  fi
done
echo "antidote_file=${antidote_file}"

if command -v fzf >/dev/null 2>&1; then
  echo "fzf_version=$(fzf --version | head -1)"
fi
if command -v zoxide >/dev/null 2>&1; then
  echo "zoxide_version=$(zoxide --version)"
fi
if command -v starship >/dev/null 2>&1; then
  echo "starship_version=$(starship --version | head -1)"
fi
if command -v direnv >/dev/null 2>&1; then
  echo "direnv_version=$(direnv version)"
fi

zsh -n "$ROOT/minimal.zshrc"
zsh -n "$ROOT/developer.zshrc"
echo "zsh_n=ok"

LAB="$(mktemp -d /tmp/fm-zsh-lab.XXXXXX)"
cleanup() {
  rm -rf "$LAB"
}
trap cleanup EXIT

cp "$ROOT/minimal.zshrc" "$LAB/.zshrc"
# One untimed start writes .zcompdump inside $LAB. The samples are the warm runs.
ZDOTDIR="$LAB" zsh -ic 'exit'

export LAB
python3 - <<'PY'
import os
import subprocess
import time

lab = os.environ["LAB"]
base = os.environ.copy()
base.pop("LAB", None)

def median_ms(cmd, env, n=20):
    samples = []
    for _ in range(n):
        t0 = time.perf_counter()
        subprocess.run(
            cmd,
            env=env,
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        samples.append((time.perf_counter() - t0) * 1000.0)
    samples.sort()
    return samples[n // 2], samples[0], samples[-1]

bare_env = base.copy()
bare_med, bare_min, bare_max = median_ms(["zsh", "-f", "-c", "exit"], bare_env)
rc_env = base.copy()
rc_env["ZDOTDIR"] = lab
rc_med, rc_min, rc_max = median_ms(["zsh", "-ic", "exit"], rc_env)
print("samples=20")
print(f"bare_median_ms={bare_med:.1f}")
print(f"bare_min_ms={bare_min:.1f}")
print(f"bare_max_ms={bare_max:.1f}")
print(f"minimal_rc_median_ms={rc_med:.1f}")
print(f"minimal_rc_min_ms={rc_min:.1f}")
print(f"minimal_rc_max_ms={rc_max:.1f}")
PY

echo "lab=ok"
