#!/usr/bin/env bash
# Fast cached lsb_release shim (agent PATH only — ~/.claude/bin precedes /usr/bin).
# The real /usr/bin/lsb_release is a /bin/sh script that forks getconf/getopt/tr/cut
# (~5 subprocs, ~0.3-0.45s under machine load). Codex core probes system info ~78×
# per boot+turn, so that tax dominates cdx launch time (~27s under load). lsb_release
# output is STATIC for a running OS, so serving it from cache is exact, not lossy.
#
# HOT PATH IS FORK-FREE: only bash's own process runs — freshness, read, and print all
# use builtins (no stat/date/cksum/cat). Cache validity is tied to /etc/os-release via
# the `-nt` builtin test: an OS upgrade rewrites that file, making every cache entry
# stale automatically. Fail-open: any miss/error runs the real binary. Bypass with
# LSB_RELEASE_NOCACHE=1.
set -u

real="/usr/bin/lsb_release"
[[ -x "$real" ]] || { echo "lsb_release: $real not found" >&2; exit 127; }

if [[ -n "${LSB_RELEASE_NOCACHE:-}" ]]; then
  exec "$real" "$@"
fi

cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/lsb_release_shim"
# Key from args via pure parameter expansion (no subprocess). Non-alnum -> _.
key="${*:-noargs}"; key="${key//[^A-Za-z0-9._-]/_}"
cache_file="$cache_dir/$key"
ref="/etc/os-release"

# Hot path: cache exists and is newer than the OS-release source of truth -> serve it
# with only builtins (mapfile read + printf), zero forks.
if [[ -f "$cache_file" && "$cache_file" -nt "$ref" ]]; then
  mapfile -t _lines < "$cache_file"
  printf '%s\n' "${_lines[@]}"
  exit 0
fi

# Miss/stale: run real once, cache atomically, passthrough. (Rare — amortized to ~0.)
out="$("$real" "$@" 2>/dev/null)"; rc=$?
if [[ $rc -eq 0 ]]; then
  if mkdir -p "$cache_dir" 2>/dev/null; then
    tmp="$cache_file.$$"
    if printf '%s\n' "$out" > "$tmp" 2>/dev/null; then
      mv -f "$tmp" "$cache_file" 2>/dev/null
      # Ensure the fresh entry is newer than $ref even if clocks are coarse.
      touch "$cache_file" 2>/dev/null
    fi
  fi
  printf '%s\n' "$out"
  exit 0
fi
exec "$real" "$@"
