#!/usr/bin/env bash
# Manual: capture V4L2/sysfs capability evidence from a live eye device.
# Not part of CI; requires local device access.
set -euo pipefail

DEVICE="${1:-/dev/lesavka_r_eye}"
OUTDIR="${2:-/tmp/lesavka-eye-capabilities}"
WAIT_SECONDS="${LESAVKA_EYE_CAP_WAIT_SECONDS:-3600}"
POLL_SECONDS="${LESAVKA_EYE_CAP_POLL_SECONDS:-1}"

mkdir -p "$OUTDIR"

deadline=$((SECONDS + WAIT_SECONDS))
while [[ ! -e "$DEVICE" ]]; do
  if (( SECONDS >= deadline )); then
    echo "eye capability probe timed out waiting for $DEVICE" >&2
    exit 124
  fi
  sleep "$POLL_SECONDS"
done

timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
device_name="$(basename "$DEVICE")"
resolved_device="$(readlink -f "$DEVICE" 2>/dev/null || printf "%s" "$DEVICE")"
prefix="$OUTDIR/${timestamp}-${device_name}"
sysfs_base="/sys/class/video4linux/$(basename "$resolved_device" 2>/dev/null || basename "$DEVICE")"

echo "capturing eye capabilities for $DEVICE (${resolved_device}) into ${prefix}-*.txt"

run_with_optional_sudo() {
  if "$@"; then
    return 0
  fi

  local status=$?
  if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then
    echo
    echo "# direct access failed with status ${status}; retrying under sudo -n"
    sudo -n "$@"
    return $?
  fi

  echo
  echo "# command exited with status ${status}"
  if [[ -e "$resolved_device" && ! -r "$resolved_device" ]]; then
    echo "# ${resolved_device} is not readable by user $(id -un)"
    echo "# groups: $(id -Gn)"
  fi
  echo "# passwordless sudo is unavailable; root or video-group access is required for full V4L2 inspection"
  return $status
}

run_probe() {
  local label="$1"
  shift
  local outfile="${prefix}-${label}.txt"
  {
    printf "# %s\n" "$label"
    printf "# device: %s\n" "$DEVICE"
    printf "# resolved_device: %s\n" "$resolved_device"
    printf "# timestamp_utc: %s\n\n" "$timestamp"
    "$@"
  } >"$outfile" 2>&1 || true
}

run_probe path-info bash -lc "printf 'device=%s\nresolved=%s\n' '$DEVICE' '$resolved_device'; printf 'ls -l: '; ls -l '$resolved_device' 2>/dev/null || true; printf 'user=%s\ngroups=%s\n' \"\$(id -un)\" \"\$(id -Gn)\""
run_probe sysfs-summary bash -lc "printf 'sysfs_base=%s\n' '$sysfs_base'; if [[ -d '$sysfs_base' ]]; then for path in name device/modalias device/uevent; do file='$sysfs_base/'\"\$path\"; if [[ -f \"\$file\" ]]; then printf -- '\n## %s\n' \"\$path\"; sed -n '1,200p' \"\$file\"; fi; done; else echo 'missing sysfs path'; fi"
run_probe v4l2-device run_with_optional_sudo v4l2-ctl --device "$DEVICE" --info
run_probe v4l2-all run_with_optional_sudo v4l2-ctl --device "$DEVICE" --all
run_probe v4l2-formats run_with_optional_sudo v4l2-ctl --device "$DEVICE" --list-formats-ext
run_probe v4l2-ctrls run_with_optional_sudo v4l2-ctl --device "$DEVICE" --list-ctrls-menus
run_probe udev udevadm info --query=all --name "$DEVICE"

echo "eye capability artifacts written under $OUTDIR"
