#!/usr/bin/env python3
"""d457-8cam - pick which D457 cameras are connected, then build + apply the
overlay ON-DEVICE in one shot. No expert, no kernel source, no PC needed:
it compiles the dtbo on the Jetson (dtc+cpp are preinstalled; the 4 dt-binding
headers are bundled) and selects it as the boot overlay for you.

Typical use (as root) - numbers are the FAKRA labels PRINTED ON THE CASE (1-8):
  sudo d457-8cam --fakra 4,2,7 --apply
    -> chassis connectors 4,2,7 have a camera; build dtbo -> /boot; select it as
       the boot overlay; then just UNPLUG POWER ~30s and boot.

Other forms:
  sudo d457-8cam                       # show current config (no change)
  sudo d457-8cam --fakra 1,2,3,4       # set connectors only (edit, no build)
  sudo d457-8cam --apply               # build+apply using the current conf
  sudo d457-8cam --build               # build only (don't touch boot overlay)
  sudo d457-8cam --slots 0,2,5 --apply # advanced: raw internal cam slots

Connectors can also be edited by hand in d457_slots.conf next to this script
(fakraN=1 -> that camera is connected). FAKRA->cam map is on the case.

Slot -> hardware (port-index stays in {0,2,4,5}, all < 6):
  cam0/1  deser 0x29 (i2c@31e0000) Port A  port-index 0
  cam2/3  deser 0x29 (i2c@31e0000) Port B  port-index 2
  cam4/5  deser 0x6b (i2c@3180000) Port A  port-index 4
  cam6/7  deser 0x6b (i2c@3180000) Port B  port-index 5
"""
import os, sys, argparse, subprocess, tempfile, shutil

HERE = os.path.dirname(os.path.realpath(__file__))  # realpath: resolve the /usr/local/bin symlink
CONF = os.path.join(HERE, "d457_slots.conf")
NAME = "tegra234-p3737-camera-d457-8cam-portab"
DEFAULT_OUT = f"/boot/{NAME}.dtbo"

# Chassis FAKRA connector (1-8, printed on the case) -> internal cam slot (0-7).
FAKRA_TO_CAM = {1: 3, 2: 2, 3: 1, 4: 0, 5: 7, 6: 6, 7: 5, 8: 4}
CAM_TO_FAKRA = {c: f for f, c in FAKRA_TO_CAM.items()}

CONF_TEMPLATE = """# D457 chassis-connector switch. 1 = camera connected, 0 = empty.
# 'fakraN' is the FAKRA number PRINTED ON THE CASE; it maps to an internal cam/deser link.
fakra1=0   # -> cam3  deser 0x29 link3  Port B
fakra2=0   # -> cam2  deser 0x29 link2  Port B
fakra3=0   # -> cam1  deser 0x29 link1  Port A
fakra4=0   # -> cam0  deser 0x29 link0  Port A
fakra5=0   # -> cam7  deser 0x6b link3  Port B
fakra6=0   # -> cam6  deser 0x6b link2  Port B
fakra7=0   # -> cam5  deser 0x6b link1  Port A
fakra8=0   # -> cam4  deser 0x6b link0  Port A
"""

def load_conf():
    """Read d457_slots.conf (fakra1..8) and return the set of internal cam slots on."""
    if not os.path.exists(CONF):
        open(CONF, "w").write(CONF_TEMPLATE)
        print(f"created {CONF} (all off)")
    on = set()
    for line in open(CONF):
        line = line.split("#", 1)[0].strip()
        if "=" not in line:
            continue
        k, v = (x.strip() for x in line.split("=", 1))
        if k.startswith("fakra") and v == "1":
            on.add(FAKRA_TO_CAM[int(k[5:])])
    return on

def write_conf(fakra_on):
    """Rewrite d457_slots.conf keeping the comments, setting fakra1..8 to 1/0."""
    if not os.path.exists(CONF):
        open(CONF, "w").write(CONF_TEMPLATE)
    out = []
    for line in open(CONF):
        s = line.split("#", 1)[0]
        if "=" in s and s.strip().startswith("fakra"):
            k = s.split("=", 1)[0].strip()
            n = int(k[5:])
            comment = ("#" + line.split("#", 1)[1].rstrip("\n")) if "#" in line else ""
            out.append(f"{k}={1 if n in fakra_on else 0}   {comment}".rstrip() + "\n")
        else:
            out.append(line)
    open(CONF, "w").write("".join(out))

def activate():
    """Point the boot overlay at the 8cam dtbo via the d457-overlay switcher."""
    sw = shutil.which("d457-overlay") or "/usr/local/bin/d457-overlay"
    if not os.path.exists(sw):
        print("  (d457-overlay not found - set the boot overlay to 8cam manually)")
        return False
    subprocess.run([sw, "8cam"], check=True)
    return True

def inc_dirs():
    """Bundled headers next to the script; fall back to the kernel source tree."""
    b = os.path.join(HERE, "include")
    if os.path.isdir(os.path.join(b, "kernel")):
        return [os.path.join(b, "kernel"), os.path.join(b, "platforms")]
    k = "/home/nomo/Project/Advantech/nvidia/adv_v61/kernel/hardware/nvidia/t23x/nv-public/include"
    return [os.path.join(k, "kernel"), os.path.join(k, "platforms")]

# ---------- overlay generation (structure = proven r750-0to6) ----------
TAB = "\t"
def ind(n): return TAB * n
STREAMS = [
    ("Depth", 0xa, "serial_a", 1280, 720, 1, False),
    ("RGB",   0xb, "serial_e", 1920, 1080, 1, True),
    ("Y8",    0xc, "serial_b", 1280, 720, 1, True),
    ("IMU",   0xd, "serial_b", 640,  480, 0, True),
]
DESERS = [
    ("i2c@31e0000", 0x29, "CAM0_PWDN", 0, 2, 0),
    ("i2c@3180000", 0x6b, "CAM1_PWDN", 4, 5, 1),
]
def cam_meta(g):
    d = DESERS[g // 4]; L = g % 4
    pidx = d[3] if L < 2 else d[4]
    port = "a" if L < 2 else "b"
    # VC must be unique across the WHOLE deserializer (not just per MIPI port) or the
    # max96712 pipe routing collides and the Port B camera gets no frames (proven: the
    # splitB overlay used globally-unique vc 8-11 for the Port B cam and streamed).
    vc_base = L * 4               # cam0=0-3, cam1=4-7, cam2=8-11, cam3=12-15 per deser
    group_base = 0x10 * (L + 1)
    ser = f"serd{d[5]}c{L}"
    return d, L, pidx, port, vc_base, group_base, ser

def gen(connected):
    def st(g): return "okay" if g in connected else "disabled"
    vi = [f'{ind(3)}tegra-capture-vi {{', f'{ind(4)}num-channels = <32>;',
          f'{ind(4)}ports {{', f'{ind(5)}status = "okay";']
    for g in range(8):
        d, L, pidx, port, vc_base, gb, ser = cam_meta(g)
        for s, stm in enumerate(STREAMS):
            ch = g*4+s; vc = vc_base+s
            vi += [f'{ind(5)}port@{ch} {{', f'{ind(6)}status = "{st(g)}";',
                   f'{ind(6)}reg = <{ch}>;', f'{ind(6)}d4xx_vi_in{ch}: endpoint {{',
                   f'{ind(7)}status = "{st(g)}";', f'{ind(7)}vc-id = <{vc}>;',
                   f'{ind(7)}port-index = <{pidx}>;', f'{ind(7)}bus-width = <2>;',
                   f'{ind(7)}remote-endpoint = <&d4xx_csi_out{ch}>;',
                   f'{ind(6)}}};', f'{ind(5)}}};']
    vi += [f'{ind(4)}}};', f'{ind(3)}}};']
    nv = [f'{ind(3)}bus@0 {{', f'{ind(4)}host1x@13e00000 {{', f'{ind(5)}nvcsi@15a00000 {{',
          f'{ind(6)}num-channels = <32>;', f'{ind(6)}#address-cells = <1>;', f'{ind(6)}#size-cells = <0>;']
    for g in range(8):
        d, L, pidx, port, vc_base, gb, ser = cam_meta(g)
        for s, stm in enumerate(STREAMS):
            ch = g*4+s
            nv += [f'{ind(6)}channel@{ch} {{', f'{ind(7)}status = "{st(g)}";',
                   f'{ind(7)}reg = <{ch}>;', f'{ind(7)}ports {{', f'{ind(8)}status = "{st(g)}";',
                   f'{ind(8)}#address-cells = <1>;', f'{ind(8)}#size-cells = <0>;',
                   f'{ind(8)}port@0 {{', f'{ind(9)}status = "{st(g)}";', f'{ind(9)}reg = <0>;',
                   f'{ind(9)}d4xx_csi_in{ch}: endpoint@{2*ch} {{', f'{ind(10)}status = "{st(g)}";',
                   f'{ind(10)}port-index = <{pidx}>;', f'{ind(10)}bus-width = <2>;',
                   f'{ind(10)}remote-endpoint = <&ds5_{ch}_out>;', f'{ind(9)}}};', f'{ind(8)}}};',
                   f'{ind(8)}port@1 {{', f'{ind(9)}status = "{st(g)}";', f'{ind(9)}reg = <1>;',
                   f'{ind(9)}d4xx_csi_out{ch}: endpoint@{2*ch+1} {{', f'{ind(10)}status = "{st(g)}";',
                   f'{ind(10)}remote-endpoint = <&d4xx_vi_in{ch}>;', f'{ind(9)}}};', f'{ind(8)}}};',
                   f'{ind(7)}}};', f'{ind(6)}}};']
    nv += [f'{ind(5)}}};', f'{ind(4)}}};']
    i2c = []
    for di, d in enumerate(DESERS):
        node, addr, pwdn, pA, pB, dindex = d
        # link-mask = bitmask of this deser's enabled slots (deser0=cam0-3, deser1=cam4-7).
        # MUST match the physically-connected cameras, or the deser is configured for
        # links that have no camera and even present cameras fail to stream (-121).
        mask = sum(1 << L for L in range(4) if (di*4+L) in connected)
        dser_st = "okay" if mask else "disabled"   # disable a deser with no cameras
        i2c += [f'{ind(4)}{node} {{', f'{ind(5)}status = "{dser_st}";', f'{ind(5)}clock-frequency = <100000>;',
                f'{ind(5)}dser{dindex}: max96712@{addr:x} {{', f'{ind(6)}status = "{dser_st}";',
                f'{ind(6)}reg = <0x{addr:x}>;', f'{ind(6)}compatible = "maxim,max96712";',
                f'{ind(6)}csi-mode = "2x4";', f'{ind(6)}link-mask = <0x{mask:x}>;', f'{ind(6)}channel = "a";',
                f'{ind(6)}pwdn-gpios = <&gpio {pwdn} GPIO_ACTIVE_HIGH>;', f'{ind(6)}force_clk0;', f'{ind(5)}}};']
        for L in range(4):
            g = di*4+L
            i2c += [f'{ind(5)}serd{dindex}c{L}: max9295_{L}@{0x40+L:x} {{', f'{ind(6)}status = "{st(g)}";',
                    f'{ind(6)}compatible = "maxim,max9295";', f'{ind(6)}reg = <0x{0x40+L:x}>;',
                    f'{ind(6)}maxim,gmsl-dser-device = <&dser{dindex}>;',
                    f'{ind(6)}external_addr_reassign;',  # RealSense: required on every serializer
                    f'{ind(5)}}};']
        # ds5 nodes in REVERSE order (imu,y8,rgb,depth; high camera first) to match the
        # proven r750-0to6 structure - keeps the video-node order rs-enum expects.
        for L in reversed(range(4)):
            g = di*4+L
            _, _, pidx, port, vc_base, gb, ser = cam_meta(g)
            for s, (ctype, off, sif, w, h, emb, ovr) in reversed(list(enumerate(STREAMS))):
                ch = g*4+s; vc = vc_base+s; reg = gb+off
                i2c += [f'{ind(5)}ds5_{ch}: ds5@{reg:x} {{', f'{ind(6)}status = "{st(g)}";',
                        f'{ind(6)}def-addr = <0x10>;', f'{ind(6)}reg = <0x{reg:x}>;']
                if ovr: i2c.append(f'{ind(6)}override_reg = <0x{gb+0xa:x}>;')
                i2c += [f'{ind(6)}compatible = "intel,d4xx";', f'{ind(6)}use_sensor_mode_id = "true";',
                        f'{ind(6)}vcc-supply = <&vdd_cam12v_poc>;', f'{ind(6)}cam-type = "{ctype}";',
                        f'{ind(6)}nvidia,gmsl-ser-device = <&{ser}>;', f'{ind(6)}nvidia,gmsl-dser-device = <&dser{dindex}>;',
                        f'{ind(6)}ports {{', f'{ind(7)}#address-cells = <1>;', f'{ind(7)}#size-cells = <0>;',
                        f'{ind(7)}port@0 {{', f'{ind(8)}reg = <0>;', f'{ind(8)}ds5_{ch}_out: endpoint {{',
                        # sensor-side port-index is the CHANNEL number (vendor r750 uses
                        # 0,1,2,3 for cam0's Depth/RGB/Y8/IMU). Giving every stream the
                        # same value makes Depth and RGB collide and streaming hangs when
                        # both run at once - the VI/nvcsi endpoints carry the real routing.
                        f'{ind(9)}vc-id = <{vc}>;', f'{ind(9)}port-index = <{ch}>;', f'{ind(9)}bus-width = <2>;',
                        f'{ind(9)}remote-endpoint = <&d4xx_csi_in{ch}>;', f'{ind(8)}}};', f'{ind(7)}}};', f'{ind(6)}}};',
                        f'{ind(6)}mode0 {{', f'{ind(7)}pixel_t = "grey_y16";', f'{ind(7)}num_lanes = "2";',
                        f'{ind(7)}csi_pixel_bit_depth = "16";', f'{ind(7)}active_w = "{w}";', f'{ind(7)}active_h = "{h}";',
                        f'{ind(7)}tegra_sinterface = "{sif}";', f'{ind(7)}mclk_khz = "24000";',
                        f'{ind(7)}pix_clk_hz = "74250000";', f'{ind(7)}line_length = "1280";',
                        f'{ind(7)}embedded_metadata_height = "{emb}";', f'{ind(6)}}};',
                        f'{ind(6)}gmsl-link {{', f'{ind(7)}src-csi-port = "b";', f'{ind(7)}dst-csi-port = "{port}";',
                        f'{ind(7)}serdes-csi-link = "a";', f'{ind(7)}csi-mode = "1x4";', f'{ind(7)}st-vc = <0>;',
                        f'{ind(7)}vc-id = <{vc}>;', f'{ind(7)}num-lanes = <2>;', f'{ind(6)}}};', f'{ind(5)}}};']
        i2c.append(f'{ind(4)}}};')
    HEADER = '''// SPDX-License-Identifier: GPL-2.0-only
// 8x D457 (2x MAX96712, 4 cams each split Port A/B). Slots toggled by d457_slots.conf.
/dts-v1/;
/plugin/;
#include <dt-bindings/clock/tegra234-clock.h>
#include <dt-bindings/gpio/tegra234-gpio.h>
#include <dt-bindings/tegra234-p3737-0000+p3701-0000.h>
#define CAM0_PWDN\tTEGRA234_MAIN_GPIO(H, 6)
#define CAM1_PWDN\tTEGRA234_MAIN_GPIO(AC, 0)
#define CAM12V_POC\tTEGRA234_MAIN_GPIO(AC, 7)
/ {
\toverlay-name = "Advantech D457 MAX96712";
\tjetson-header-name = "Jetson AGX CSI Connector";
\tcompatible = JETSON_COMPATIBLE;
\tfragment@1 {
\t\ttarget-path = "/";
\t\t__overlay__ {
\t\t\tvdd_cam12v_poc: regulator-vdd-cam12v-poc {
\t\t\t\tcompatible = "regulator-fixed";
\t\t\t\tregulator-name = "vdd-cam12v-poc";
\t\t\t\tregulator-min-microvolt = <12000000>;
\t\t\t\tregulator-max-microvolt = <12000000>;
\t\t\t\tgpio = <&gpio CAM12V_POC GPIO_ACTIVE_HIGH>;
\t\t\t\tenable-active-high;
\t\t\t};
\t\t};
\t};
\tfragment@0 {
\t\ttarget-path = "/";
\t\t__overlay__ {
'''
    FOOTER = f'{ind(3)}}};\n{ind(2)}}};\n{ind(1)}}};\n}};\n'
    return HEADER + "\n".join(vi) + "\n" + "\n".join(nv) + "\n" + "\n".join(i2c) + "\n" + FOOTER

def build(dts_path, out):
    pre = tempfile.mktemp(suffix=".pre.dts")
    cpp = ["cpp", "-nostdinc", "-undef", "-x", "assembler-with-cpp", "-D__DTS__",
           "-DLINUX_VERSION=600", "-DTEGRA_HOST1X_DT_VERSION=2"]
    for d in inc_dirs():
        cpp += ["-I", d]
    cpp += [dts_path, "-o", pre]
    subprocess.run(cpp, check=True)
    subprocess.run(["dtc", "-@", "-O", "dtb", "-o", out, pre],
                   check=True, stderr=subprocess.DEVNULL)
    os.remove(pre)
    # Flush to disk: UEFI reads the .dtbo straight off the block device at boot, so an
    # unflushed write is invisible if power is pulled right after -> the PREVIOUS config
    # silently boots. (Seen on HW: new dtbo on disk, old camera set in the live DT.)
    fd = os.open(out, os.O_RDONLY); os.fsync(fd); os.close(fd)
    os.sync()

SLOT_INFO = {   # fakra -> (deser addr, link, MIPI port)
    1: ("0x29", 3, "B"), 2: ("0x29", 2, "B"), 3: ("0x29", 1, "A"), 4: ("0x29", 0, "A"),
    5: ("0x6b", 3, "B"), 6: ("0x6b", 2, "B"), 7: ("0x6b", 1, "A"), 8: ("0x6b", 0, "A"),
}

# Advantech wordmark, flat solid blocks (no 3-D shadow). All caps, and the V and A
# share a stem - the detail in the official mark. Rendered white on #004280 blue.
LOGO_UNI = [
 " ████  █████  ██  █████  ██  ██ ██████ ██████  █████ ██  ██",
 "██  ██ ██  ██ ██  ██  ██ ███ ██   ██   ██     ██     ██  ██",
 "██████ ██  ██ ██  ██████ ██████   ██   █████  ██     ██████",
 "██  ██ ██  ██  █████  ██ ██ ███   ██   ██     ██     ██  ██",
 "██  ██ █████    ████  ██ ██  ██   ██   ██████  █████ ██  ██",
]
LOGO_ASC = [
 " ####  #####  ##  #####  ##  ## ###### ######  ##### ##  ##",
 "##  ## ##  ## ##  ##  ## ### ##   ##   ##     ##     ##  ##",
 "###### ##  ## ##  ###### ######   ##   #####  ##     ######",
 "##  ## ##  ##  #####  ## ## ###   ##   ##     ##     ##  ##",
 "##  ## #####    ####  ## ##  ##   ##   ######  ##### ##  ##",
]

def menu(fakra_on):
    """BIOS-style setup screen. Returns the chosen set, or None if the user quit."""
    import curses, locale
    locale.setlocale(locale.LC_ALL, "")
    uni = "utf" in (locale.getpreferredencoding() or "").lower()
    logo = LOGO_UNI if uni else LOGO_ASC

    def loop(scr):
        curses.curs_set(0)
        C = {}
        if curses.has_colors():
            curses.start_color()
            try: curses.use_default_colors()
            except curses.error: pass
            # Advantech blue #004280 -> exact if the terminal lets us redefine a color,
            # else the closest 256-colour navy, else plain blue (which reads too light).
            navy = curses.COLOR_BLUE
            try:
                if curses.can_change_color() and curses.COLORS > 16:
                    curses.init_color(99, 0, 259, 502)   # 0,66,128 scaled to 0-1000
                    navy = 99
                elif curses.COLORS >= 256:
                    navy = 24                            # #005f87, nearest dark navy
            except curses.error:
                pass
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)   # body: black bg
            curses.init_pair(2, curses.COLOR_WHITE, navy)                 # logo: Advantech blue
            curses.init_pair(3, curses.COLOR_WHITE,  curses.COLOR_BLACK)  # bars
            curses.init_pair(4, curses.COLOR_WHITE,  curses.COLOR_BLACK)  # ON / accents
            C = {k: curses.color_pair(k) for k in (1, 2, 3, 4)}
        else:
            C = {1: 0, 2: curses.A_REVERSE, 3: curses.A_BOLD, 4: curses.A_BOLD}

        sel, on = 0, set(fakra_on)
        while True:
            scr.bkgd(" ", C[1])
            scr.erase()
            h, w = scr.getmaxyx()
            W = min(78, w - 2)
            x = max(0, (w - W) // 2)
            put = lambda yy, xx, t, a=0: (yy < h and xx + len(t) <= w) and scr.addstr(yy, xx, t, a)

            # Layout budget: title(1) + table(11) + status(1) + help(2) = 15 baseline.
            # Logo block costs 8 more; the two hint lines are dropped first when short.
            show_logo = h >= 25 and w >= len(logo[0]) + 6
            show_hint = h >= (23 + 4 if show_logo else 19)
            y = 0
            # ---- title bar ----
            put(y, 0, " Advantech Camera Configuration Utility".ljust(w - 1), C[3] | curses.A_BOLD); y += 1
            # ---- logo ----
            if show_logo:
                LW = len(logo[0]) + 4                      # blue plate, like the real mark
                lx = max(0, (w - LW) // 2)
                put(y, lx, " " * LW, C[2]); y += 1
                for ln in logo:
                    put(y, lx, "  " + ln.ljust(LW - 4) + "  ", C[2] | curses.A_BOLD); y += 1
                put(y, lx, " " * LW, C[2]); y += 1
                sub = "D457  /  MAX96712  GMSL Camera Setup"
                put(y, max(0, (w - len(sub)) // 2), sub, C[1] | curses.A_BOLD); y += 2
            else:
                y += 1

            # ---- table ----
            put(y, x, "+" + "-" * (W - 2) + "+", C[1]); y += 1
            put(y, x, "|" + "  Connector     State      Deserializer   Link   MIPI Port".ljust(W - 2) + "|",
                C[1] | curses.A_BOLD); y += 1
            put(y, x, "+" + "-" * (W - 2) + "+", C[1]); y += 1
            top = y
            for i in range(8):
                f = i + 1
                d, lk, pt = SLOT_INFO[f]
                st = "[*] ON " if f in on else "[ ] OFF"
                row = f"   FAKRA {f}       {st}       {d}            {lk}      Port {pt}"
                put(y, x, "|", C[1])
                attr = (curses.A_REVERSE | curses.A_BOLD) if i == sel else (C[4] if f in on else C[1])
                put(y, x + 1, row.ljust(W - 2)[:W - 2], attr)
                put(y, x + W - 1, "|", C[1]); y += 1
            put(y, x, "+" + "-" * (W - 2) + "+", C[1]); y += 1

            # ---- status ----
            lst = ",".join(str(v) for v in sorted(on)) if on else "none"
            put(y, x, f"  Cameras enabled : {len(on)}   (FAKRA {lst})".ljust(W), C[4] | curses.A_BOLD)
            if show_hint:
                put(y + 2, x, "  Enable only connectors that really have a camera -".ljust(W), C[1])
                put(y + 3, x, "  a mismatch stops the connected cameras from streaming.".ljust(W), C[1])

            # ---- help bars ----
            put(h - 2, 0, " UP/DOWN Select    SPACE/LEFT/RIGHT Toggle    A All    N None".ljust(w - 1), C[3])
            put(h - 1, 0, " F10 / S  Save & Apply                        ESC / Q  Exit".ljust(w - 1), C[3])
            scr.refresh()

            k = scr.getch()
            if k in (curses.KEY_UP, ord("k")):
                sel = (sel - 1) % 8
            elif k in (curses.KEY_DOWN, ord("j")):
                sel = (sel + 1) % 8
            elif k in (ord(" "), curses.KEY_LEFT, curses.KEY_RIGHT, ord("\t")):
                f = sel + 1
                on.discard(f) if f in on else on.add(f)
            elif k in (ord("a"), ord("A")):
                on = set(range(1, 9))
            elif k in (ord("n"), ord("N")):
                on = set()
            elif k in (curses.KEY_F10, ord("s"), ord("S"), curses.KEY_ENTER, 10, 13):
                return on
            elif k in (27, ord("q"), ord("Q")):
                return None

    if not os.environ.get("TERM"):
        os.environ["TERM"] = "linux"      # sudo often strips TERM (serial consoles too)
    try:
        return curses.wrapper(loop)
    except curses.error as e:
        sys.exit(f"cannot open the setup screen ({e}).\n"
                 f"Use the command line instead, e.g.:  sudo d457-8cam --fakra 4,2,7 --apply")


def main():
    ap = argparse.ArgumentParser(
        description="Toggle 8 D457 slots and build/apply the overlay on-device.")
    ap.add_argument("--menu", action="store_true",
                    help="BIOS-style setup screen (default when run with no arguments)")
    ap.add_argument("--fakra", metavar="LIST",
                    help='which CHASSIS FAKRA connectors (1-8, as printed on the case) have '
                         'a camera, e.g. --fakra 4,2,7 (sets those ON, the rest OFF).')
    ap.add_argument("--slots", metavar="LIST",
                    help='advanced: raw internal cam slots 0-7 (bypasses the FAKRA map).')
    ap.add_argument("--build", action="store_true", help="compile the .dtbo to --out")
    ap.add_argument("--apply", action="store_true",
                    help="compile, install to /boot, AND select it as the boot overlay "
                         "(one-shot; then just power-cycle)")
    ap.add_argument("--out", default=DEFAULT_OUT, help=f"output .dtbo (default {DEFAULT_OUT})")
    ap.add_argument("--dts", default=tempfile.gettempdir() + f"/{NAME}.dts",
                    help="where to write the generated .dts")
    args = ap.parse_args()

    # No arguments (or --menu) on a terminal -> BIOS-style setup screen
    if args.menu or not (args.fakra or args.slots or args.build or args.apply):
        if not sys.stdin.isatty():
            sys.exit("no TTY for the setup screen - use: d457-8cam --fakra <list> --apply")
        cur = set(CAM_TO_FAKRA[c] for c in load_conf())
        chosen = menu(cur)
        if chosen is None:
            print("cancelled - nothing changed")
            return
        write_conf(chosen)
        args.apply = True          # Save & Apply
    # --fakra (chassis connectors) or --slots (raw cam) override the conf; both write fakra1..8
    if args.fakra is not None:
        try:
            fk = set(int(x) for x in args.fakra.replace(",", " ").split())
        except ValueError:
            sys.exit("--fakra must be numbers 1-8, e.g. --fakra 4,2,7")
        if not fk <= set(range(1, 9)):
            sys.exit("--fakra values must be 1-8 (the numbers on the case)")
        write_conf(fk)
    elif args.slots is not None:
        try:
            sel = set(int(x) for x in args.slots.replace(",", " ").split())
        except ValueError:
            sys.exit("--slots must be numbers 0-7")
        if not sel <= set(range(8)):
            sys.exit("--slots values must be 0-7")
        write_conf(set(CAM_TO_FAKRA[c] for c in sel))   # convert cam -> fakra for the conf

    on = load_conf()
    dts = gen(on)
    open(args.dts, "w").write(dts)
    # self-check: every ds5 node of an ON slot has status okay, OFF slot disabled
    for g in range(8):
        want = "okay" if g in on else "disabled"
        tag = f'ds5_{g*4}: ds5@'
        i = dts.find(tag)
        assert i > 0 and dts[i:i+120].split('status = "')[1].startswith(want), \
            f"slot cam{g} status != {want}"

    print(f"FAKRA connectors ON: {sorted(CAM_TO_FAKRA[c] for c in on) if on else '(none)'}"
          f"   (internal cam {sorted(on) if on else '-'})")
    if not (args.build or args.apply):
        print(f"wrote {args.dts}")
        print("re-run with --apply to build + install + select as boot overlay")
        return
    try:
        build(args.dts, args.out)
    except PermissionError:
        sys.exit(f"cannot write {args.out} - run with sudo")
    except subprocess.CalledProcessError as e:
        sys.exit(f"compile failed: {e}")
    print(f"built {args.out}")
    if not args.apply:
        print("next: sudo d457-overlay 8cam ; then FULL power-cycle the board")
        return
    try:
        activate()
    except (subprocess.CalledProcessError, PermissionError):
        sys.exit("could not set the boot overlay - run: sudo d457-overlay 8cam")
    print("")
    print("=== DONE. Now UNPLUG POWER for ~30s and boot again. ===")
    print("(a normal reboot can wedge the MAX96712 - a full power cycle is required)")

if __name__ == "__main__":
    main()
