#!/usr/bin/env bash
# Records a tool the sandbox image does not provide. Never fails the caller.
set -uo pipefail

case "${1:-}" in
  record) ;;
  *) echo "usage: sandbox-toolgap record <tool>" >&2; exit 2 ;;
esac

tool="${2:-}"
[ -n "$tool" ] || exit 0

# Absent on purpose. Reporting these as gaps would ask an agent to put the
# escalation and host-mutation paths back into the image.
case "$tool" in
  sudo|deck-sudo|pkexec|run0|su|doas|setcap|setpriv|capsh|chroot|unshare|nsenter|\
  systemctl|systemd-run|journalctl|loginctl|machinectl|busctl|reboot|shutdown|halt|poweroff|kexec|\
  ip|ifconfig|iptables|ip6tables|nft|iptables-nft|route|tc|brctl|resolvectl|networkctl|nmcli|\
  tailscale|tailscaled|wg|wg-quick|sshd|ufw|firewall-cmd|\
  mount|umount|mkfs|fdisk|parted|losetup|swapon|swapoff|modprobe|insmod|rmmod|sysctl|dmesg|\
  podman|docker|nerdctl|buildah|skopeo|crictl|kubectl|\
  chromium|chrome|google-chrome|firefox|webkit|playwright)
    echo "$tool: command not found — absent from the sandbox by design, not a gap"
    exit 0
    ;;
esac

file="${SANDBOX_TOOLGAP_FILE:-/sandbox/toolgap/gaps.jsonl}"
mkdir -p "$(dirname "$file")" 2>/dev/null || { echo "$tool: command not found"; exit 0; }

printf '{"ts":"%s","sandboxId":"%s","image":"%s","tool":"%s","cwd":"%s"}\n' \
  "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
  "${SANDBOX_ID:-unknown}" \
  "${SANDBOX_IMAGE:-unknown}" \
  "${tool//\"/\\\"}" \
  "${PWD//\"/\\\"}" \
  >>"$file" 2>/dev/null || true

echo "$tool: command not found — recorded as a sandbox tool gap"
exit 0
