#!/bin/bash
# Select which MAX96712/D457 overlay boots, then FULL power-cycle the board.
set -e
CONF=/boot/extlinux/extlinux.conf
declare -A OV=(
  [r750]=/boot/tegra234-p3737-camera-d457-r750-0to6.dtbo
  [splitB]=/boot/tegra234-p3737-camera-d457-r750-0to6-splitB.dtbo
  [deserB]=/boot/tegra234-p3737-camera-d457-r750-0to6-deserB.dtbo
  [8cam]=/boot/tegra234-p3737-camera-d457-8cam-portab.dtbo
)
sel="${1:-}"
case "$sel" in r750|splitB|deserB|8cam) ;; *) sel="" ;; esac
if [ -z "$sel" ]; then
  echo "usage: sudo d457-overlay {r750|splitB|deserB|8cam}"
  echo "  r750    : baseline 3x D457 on deser 0x29, single deser, all Port A"
  echo "  splitB  : 3x D457 on deser 0x29, cam2 on Port B (bandwidth split test)"
  echo "  deserB  : 3x D457 on the 2nd deser 0x6b (i2c@3180000), Port A, port-index 4"
  echo "  8cam    : 2x deser (0x29+0x6b), up to 8 cams, 2+2 split Port A/B"
  echo -n "  current: "; grep -iE '^\s*OVERLAYS' "$CONF" 2>/dev/null || echo "(none)"
  exit 1
fi
if grep -qE '/boot/tegra234-p3737-camera-d457-[A-Za-z0-9-]+\.dtbo' "$CONF"; then
  # a d457 overlay is already there -> swap just that token (keep co-overlays)
  sed -i -E "s#/boot/tegra234-p3737-camera-d457-[A-Za-z0-9-]+\.dtbo#${OV[$sel]}#g" "$CONF"
elif grep -qiE '^[[:space:]]*OVERLAYS' "$CONF"; then
  # an OVERLAYS line exists (other overlays) -> append the d457 dtbo to the first one
  sed -i -E "0,/^[[:space:]]*OVERLAYS/ s#(^[[:space:]]*OVERLAYS[[:space:]]+[^[:space:]#]*)#\1,${OV[$sel]}#" "$CONF"
else
  # FRESH machine: no OVERLAYS line at all -> add one under the DEFAULT boot label.
  # A base FDT must also be named, otherwise UEFI has no DTB to apply the overlay to
  # and the camera nodes never reach the kernel (this is what jetson-io adds too).
  DEF=$(awk 'tolower($1)=="default"{print $2; exit}' "$CONF")
  FDT=""
  if ! awk -v lbl="$DEF" '$1=="LABEL"&&$2==lbl{i=1} i&&$1=="FDT"{f=1} i&&$1=="LABEL"&&$2!=lbl{i=0} END{exit !f}' "$CONF"; then
    board=$(tr '\0' '\n' </proc/device-tree/compatible | head -1)   # e.g. nvidia,p3737-0000+p3701-0005
    cand="/boot/dtb/kernel_tegra234-${board#nvidia,}-nv.dtb"
    [ -f "$cand" ] || cand=$(ls /boot/dtb/kernel_tegra234-*.dtb 2>/dev/null | head -1)
    [ -n "$cand" ] && [ -f "$cand" ] && FDT="FDT $cand"
  fi
  awk -v lbl="$DEF" -v ov="OVERLAYS ${OV[$sel]}" -v fdt="$FDT" '
    { print }
    $1=="LABEL" && $2==lbl { inlbl=1 }
    inlbl && $1=="LINUX" && fdt != "" { print "      " fdt; fdt="" }
    inlbl && $1=="APPEND" { print "      " ov; inlbl=0 }
  ' "$CONF" > "$CONF.d457tmp" && mv "$CONF.d457tmp" "$CONF"
fi
# keep the boot menu label consistent + reflecting the active overlay (only the
# jetson-io/DEFAULT label; never the 'primary kernel' one)
sed -i -E "s#^(\s*MENU LABEL )(Custom Header Config.*|Advantech D457 MAX96712.*)#\1Advantech D457 MAX96712 [$sel]#" "$CONF"
sync   # extlinux is read by UEFI off the raw device; unflushed edits are lost on power-cut
echo "Overlay set to '$sel' -> ${OV[$sel]}"
grep -nE '^\s*OVERLAYS' "$CONF"
echo "NOW: full power-cycle the board (unplug ~30s), not just reboot."
