#!/usr/bin/env bash
set -euo pipefail

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || { echo "[ERR] Missing command: $1" >&2; exit 1; }
}

need_cmd rs-enumerate-devices
need_cmd awk
need_cmd sed
need_cmd grep

realsense_output() {
  rs-enumerate-devices 2>/dev/null || true
}

is_realsense_present() {
  local out
  out="$(realsense_output)"
  echo "$out" | grep -qi "Intel RealSense"
}

print_bool() {
  if is_realsense_present; then
    echo "true"
  else
    echo "false"
  fi
}

list_serials() {
  local out
  out="$(realsense_output)"
  if ! echo "$out" | grep -qi "Intel RealSense"; then
    return 0
  fi

  echo "$out" \
    | awk -F':' '/Serial Number/ {print $2}' \
    | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' \
    | grep -v '^$' \
    | awk '!seen[$0]++'
}

# Apply USB power settings to the RealSense sysfs path + its parent hub
apply_fix() {
  local RS_OUT SERIAL PHY USB_NODE PARENT_HUB DEV_SYS HUB_SYS

  RS_OUT="$(realsense_output)"
  if ! echo "$RS_OUT" | grep -qi "Intel RealSense"; then
    # No device: just print false
    echo "false"
    return 0
  fi

  SERIAL="$(echo "$RS_OUT" | awk -F':' '/Serial Number/ {gsub(/[ \t]/,"",$2); print $2; exit}')"
  PHY="$(echo "$RS_OUT" | awk -F':' '/Physical Port/ {print $2; exit}' | sed 's/^[ \t]*//')"

  # Extract USB node like "2-2.3" from Physical Port
  USB_NODE="$(echo "$PHY" | grep -oE '/usb[0-9]+/[^ ]+' | sed -E 's#.*/usb[0-9]+/##' | cut -d'/' -f2 | head -n1 || true)"
  if [[ -z "${USB_NODE:-}" ]]; then
    USB_NODE="$(echo "$PHY" | grep -oE 'usb[0-9]+/[0-9]+-[0-9]+(\.[0-9]+)?' | sed 's#usb[0-9]+/##' | head -n1 || true)"
  fi

  if [[ -z "${USB_NODE:-}" ]]; then
    # Can't map sysfs; still detected though
    echo "true"
    return 0
  fi

  PARENT_HUB="${USB_NODE%%.*}"
  DEV_SYS="/sys/bus/usb/devices/${USB_NODE}"
  HUB_SYS="/sys/bus/usb/devices/${PARENT_HUB}"

  # Disable autosuspend globally (optional)
  echo -1 | sudo tee /sys/module/usbcore/parameters/autosuspend >/dev/null || true

  apply_power_fix() {
    local path="$1"
    [[ -d "$path" ]] || return 0
    [[ -e "$path/power/control" ]] && echo on | sudo tee "$path/power/control" >/dev/null || true
    [[ -e "$path/power/autosuspend" ]] && echo -1 | sudo tee "$path/power/autosuspend" >/dev/null || true
    [[ -e "$path/power/autosuspend_delay_ms" ]] && echo 0 | sudo tee "$path/power/autosuspend_delay_ms" >/dev/null || true
  }

  apply_power_fix "$HUB_SYS"
  apply_power_fix "$DEV_SYS"

  # Final verification
  print_bool
}

usage() {
  cat <<'EOF'
Usage:
  bash fix_realsense_usb.sh --check   # prints true/false only
  bash fix_realsense_usb.sh --fix     # applies fix then prints true/false
  bash fix_realsense_usb.sh --serials # prints available RealSense serials, one per line
Default: --fix
EOF
}

mode="${1:---fix}"

case "$mode" in
  --check)
    print_bool
    ;;
  --fix)
    apply_fix
    ;;
  --serials|--list-serials)
    list_serials
    ;;
  -h|--help)
    usage
    ;;
  *)
    usage >&2
    exit 1
    ;;
esac
