#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2015-2016, 2026 InterGenJLU
#
# nvidia 580.159.04 — NVIDIA proprietary GPU driver (mirror-only, extra/ tier)
# Upstream:
#   open-gpu-kernel-modules: https://github.com/NVIDIA/open-gpu-kernel-modules
#   NVIDIA Linux .run:       https://us.download.nvidia.com/XFree86/Linux-x86_64/
#
# Bundle layout (matches Arch nvidia-open-dkms + nvidia-utils pattern):
#   source[0]: NVIDIA open-gpu-kernel-modules tarball (GPLv2/MIT)
#               -> compiled at BUILD time in-chroot to validate; source tree
#                  shipped to /usr/src/nvidia-open-${ver}/ for DKMS-style
#                  rebuild against the user's installed kernel at pkm install.
#               -> the build-chroot compile is a smoke test: we do NOT ship
#                  the chroot's compiled .ko files. Reason: the chroot's
#                  module-signing key is the kernel's ephemeral build key,
#                  not the user's MOK; modules signed in-chroot would not
#                  load on the user's machine under MODULE_SIG_FORCE=y.
#
#   source[1]: NVIDIA Linux .run installer (closed-source userspace + GSP fw)
#               -> extracted at BUILD time via --extract-only (NEVER executes
#                  the nvidia-installer's interactive installer script);
#                  userspace .so files + GSP firmware + tools + udev rules
#                  + systemd units + libglvnd vendor JSON files are pulled
#                  out of the extracted directory and laid into $DESTDIR.
#
# Default-state posture (Holy Grail filter):
#   nvidia-persistenced.service  — shipped DISABLED. The post-install hook
#                                  does NOT call `systemctl enable`. Compute
#                                  users opt in explicitly.
#   nvidia-suspend.service       — shipped ENABLED. Required for working
#                                  Wayland suspend; disabling it corrupts
#                                  the display after resume. Operator-
#                                  direct ENABLED per 2026-05-28 directive.
#   nvidia-resume.service        — shipped ENABLED. Same rationale.
#   nvidia-hibernate.service     — shipped ENABLED. Same rationale.
#
# Mirror-only (iso_include: false) — package never lands on an ISO without
# operator action. Secure-default belt-and-suspenders still applies.
#
# Module signing: the post-install hook signs each freshly built .ko with
# the per-machine MOK at /var/lib/intergen/mok/mok.{key,crt} (generated by
# Forge installer/backend/mok.py). MOK is enrolled at first-boot via
# MokManager; thereafter modules signed with that key load under
# MODULE_SIG_FORCE=y. The InterGenOS distro PIV-slot-9c key NEVER touches
# user systems — only the per-machine MOK.
#
# Module options affecting boot live on the kernel cmdline (PD lens —
# operator-direct 2026-05-28). Ships /etc/kernel/cmdline.d/40-nvidia.conf
# with `nvidia-drm.modeset=1 nvidia-drm.fbdev=1`. The nouveau blacklist
# stays in modprobe.d (module-loader policy, not kernel param). UKI
# rebuild triggered by linux-kernel post-install when cmdline.d fragments
# change; transparent operation captured by build-trace.

BUILD_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

# Source-layout constants
NV_VERSION="580.159.04"
RUN_FILE="NVIDIA-Linux-x86_64-${NV_VERSION}.run"

configure() {
    set -e

    # The orchestrator extracts source[0] (open-gpu-kernel-modules) into
    # our cwd. Validate the upstream tree layout.
    test -d kernel-open || { echo "ERROR: source[0] missing kernel-open/" >&2; return 1; }
    test -d src         || { echo "ERROR: source[0] missing src/"         >&2; return 1; }

    OPEN_SRC="$PWD"
    SRC_PARENT="$(dirname "$PWD")"

    # Extract NVIDIA .run installer into a sibling directory. The .run is a
    # makeself self-extracting shell script. --extract-only lands its
    # payload into a directory without executing the nvidia-installer
    # interactive script (which would attempt to write to /lib/modules,
    # /etc/modprobe.d, etc. on the BUILD HOST — wrong target for a chroot
    # build pipeline).
    cd "$SRC_PARENT"
    rm -rf nvidia-run
    sh "${IGOS_SOURCES}/${RUN_FILE}" --extract-only --target nvidia-run
    NV_RUN_SRC="$SRC_PARENT/nvidia-run"

    # Stash paths for build() + do_install()
    echo "$OPEN_SRC"   > /tmp/.nvidia-build-open-src
    echo "$NV_RUN_SRC" > /tmp/.nvidia-build-run-src
}

build() {
    set -e
    OPEN_SRC=$(cat /tmp/.nvidia-build-open-src)

    # Build open-gpu-kernel-modules in the chroot as a smoke test. The
    # chroot has the kernel staged at /usr/src/linux-6.18.10/ + symlink
    # /lib/modules/6.18.10-igos/build via linux-kernel-pass2's do_install.
    # The compiled .ko files surface upstream-compile breakage at build
    # time BEFORE the broken source tree reaches user machines.
    cd "$OPEN_SRC"

    # KERNEL_UNAME is the kernel's uname -r equivalent. In the build
    # chroot there is no "running" kernel; use the version of the kernel
    # package this package depends on (linux-kernel-pass2, 6.18.10-igos).
    export KERNEL_UNAME="6.18.10-igos"

    # ---- SMOKE TEST: open-gpu-kernel-modules compile (FATAL on failure) ----
    # 580.159.04 carries NVIDIA's own conftest+macro fix for the kernel-6.18
    # get_dev_pagemap() 1-arg signature change (kernel commit dd57f5feb19a):
    # conftest probe get_dev_pagemap_has_pgmap_arg + the NV_GET_DEV_PAGEMAP
    # macro dispatch (nv-linux.h) emit the correct call on both pre- and
    # post-6.18 kernels. So this compiles clean against our 6.18.10.
    #
    # No de-fatalize: nvidia is held to the same standard as every other
    # package. A compile failure HARD-fails the build (set -e) so any 6.18
    # break against our .config surfaces loudly here rather than reaching a
    # user's DKMS rebuild. The chroot-built .ko is a smoke-test artifact and
    # is NOT shipped (signing-key mismatch); do_install ships the source tree
    # to /usr/src/nvidia-open-${ver}/ for the per-machine DKMS-style rebuild.
    make modules -j"${IGOS_JOBS}" \
        SYSSRC=/usr/src/linux-6.18.10 \
        SYSOUT=/usr/src/linux-6.18.10
    echo "nvidia smoke-test: open-gpu-kernel-modules compiled against 6.18.10 — OK"
    # Ship source-only — clean the chroot-built artifacts. Cross-distro cite:
    # Arch's nvidia-open-dkms ships the source tree to /usr/src/nvidia-open-${ver}/
    # for the same DKMS rebuild path; we mirror.
    make clean
}

check() {
    set -e
    # The build() compile IS the check — if `make modules` succeeded, the
    # source tarball compiles against the kernel headers we ship. Runtime
    # tests are not possible inside the chroot (no GPU, no MOK, no real
    # /sys/class/drm). Same environment-bounded shape as docker / runc.
    pkg_run_tests "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/package.yml" \
        true
}

do_install() {
    set -e
    OPEN_SRC=$(cat /tmp/.nvidia-build-open-src)
    NV_RUN_SRC=$(cat /tmp/.nvidia-build-run-src)

    # ---- Open kernel module source tree -> /usr/src/ -----------------------
    # Ship the source tree; the pkm post-install hook rebuilds on the
    # user's machine against the user's kernel. The chroot-built .ko files
    # are intentionally NOT shipped (signing key mismatch).
    install -d -m 755 "$DESTDIR/usr/src"
    cp -a "$OPEN_SRC" "$DESTDIR/usr/src/nvidia-open-${NV_VERSION}"

    # ---- Userspace libraries from .run -> /usr/lib/ ------------------------
    # NVIDIA .run extract puts versioned .so files at the top level. We
    # install each versioned blob plus parse the manifest for symlinks.
    #
    # GLVND SPLIT (GBC001 libEGL blocker fix, 2026-06-05) ------------------
    # NVIDIA bundles its OWN copy of the libglvnd client dispatchers — e.g.
    # libEGL.so.580.159.04 (and libEGL.so.1.1.0), both with embedded SONAME
    # libEGL.so.1. InterGenOS is a glvnd system: packages/desktop/libglvnd
    # already owns libEGL.so.1 (libEGL.so.1.1.0). If we ALSO ship NVIDIA's
    # copy, ldconfig ranks "580.159.04" above libglvnd's "1.1.0" and points
    # /usr/lib/libEGL.so.1 at NVIDIA's dispatcher — which cannot init EGL on
    # a non-NVIDIA GPU (amdgpu/i915) -> gnome-shell fails -> GDM crash-loop
    # on the installed system. So we must NOT ship the libglvnd-owned client
    # sonames; only NVIDIA's *_nvidia vendor libs (libEGL_nvidia.so.0,
    # libGLX_nvidia.so.0, ...), which libglvnd routes to via the vendor JSON
    # at /usr/share/glvnd/egl_vendor.d/10_nvidia.json. This is exactly how
    # Arch (nvidia-utils vs libglvnd), Fedora and Debian split the packages,
    # and it is safe on real NVIDIA hardware (EGL/GLX dispatch through glvnd
    # -> *_nvidia). Complements the install-time GPU gate in
    # installer/backend/packages.py (which keeps nvidia off non-NVIDIA HW
    # entirely); this split additionally guarantees no hijack even WHEN
    # nvidia is correctly installed on an NVIDIA box.
    #
    # Filename stems owned by libglvnd (must never come from nvidia):
    #   libEGL libGL libGLX libOpenGL libGLESv1_CM libGLESv2 libGLdispatch
    # The regex anchors `lib<STEM>.so.` so it matches the bare client libs
    # but NOT the *_nvidia vendor libs (libEGL_nvidia.so.*, libGLX_nvidia.*),
    # nor the lowercase libglxserver_nvidia.
    install -d -m 755 "$DESTDIR/usr/lib"
    GLVND_OWNED_RE='^lib(EGL|GL|GLX|OpenGL|GLESv1_CM|GLESv2|GLdispatch)\.so\.'
    for so in "$NV_RUN_SRC"/*.so.${NV_VERSION}; do
        [ -f "$so" ] || continue
        base=$(basename "$so")
        if printf '%s\n' "$base" | grep -Eq "$GLVND_OWNED_RE"; then
            echo "[nvidia:do_install] glvnd-split: NOT shipping libglvnd-owned" \
                 "$base (libglvnd provides the libEGL.so.1 dispatcher; nvidia" \
                 "registers via egl_vendor.d/10_nvidia.json -> libEGL_nvidia.so.0)"
            continue
        fi
        install -m 755 "$so" "$DESTDIR/usr/lib/$base"
    done

    # Parse $NV_RUN_SRC/.manifest to create the symlinks NVIDIA's
    # nvidia-installer would create. Manifest line format:
    #   /path/to/dest <perm> <owner> <group> <type> [<linktarget>]
    # We only handle SYMLINK; the libraries themselves are already in
    # place from the loop above. Defensive: never recreate a libglvnd-owned
    # client symlink (libEGL.so.1, libEGL.so, ...) — same split as above.
    if [ -f "$NV_RUN_SRC/.manifest" ]; then
        while read -r dest perm owner group ftype linktarget; do
            case "$ftype" in
                SYMLINK)
                    destbase=$(basename "$dest")
                    if printf '%s\n' "$destbase" | grep -Eq "$GLVND_OWNED_RE"; then
                        continue
                    fi
                    target_dir="$DESTDIR/$(dirname "$dest")"
                    install -d -m 755 "$target_dir"
                    ln -sf "$linktarget" "$DESTDIR/$dest"
                    ;;
            esac
        done < "$NV_RUN_SRC/.manifest"
    fi

    # ---- GSP firmware -> /usr/lib/firmware/nvidia/${ver}/ ------------------
    # GSP firmware (GPU System Processor) is REQUIRED on Turing-and-newer
    # silicon. NVIDIA ships per-architecture .bin files (gsp_tu10x, gsp_ga10x,
    # gsp_ad10x, gsp_gh100, gsp_gb20x). The kernel module's firmware
    # loader picks the matching blob at module load.
    install -d -m 755 "$DESTDIR/usr/lib/firmware/nvidia/${NV_VERSION}"
    if [ -d "$NV_RUN_SRC/firmware" ]; then
        for fw in "$NV_RUN_SRC/firmware"/gsp_*.bin; do
            [ -f "$fw" ] || continue
            install -m 644 "$fw" "$DESTDIR/usr/lib/firmware/nvidia/${NV_VERSION}/"
        done
    fi

    # ---- Userspace tools -> /usr/bin/ --------------------------------------
    install -d -m 755 "$DESTDIR/usr/bin"
    for tool in nvidia-smi nvidia-settings nvidia-persistenced nvidia-xconfig \
                nvidia-modprobe nvidia-cuda-mps-control nvidia-cuda-mps-server \
                nvidia-debugdump nvidia-bug-report.sh; do
        if [ -f "$NV_RUN_SRC/$tool" ]; then
            install -m 755 "$NV_RUN_SRC/$tool" "$DESTDIR/usr/bin/$tool"
        fi
    done

    # nvidia-modprobe MUST be setuid root — it creates /dev/nvidia* device
    # nodes on first access. The kernel refuses to use it without setuid.
    # Cross-distro cite: Arch + Fedora + Debian all set 4755 on this binary.
    [ -f "$DESTDIR/usr/bin/nvidia-modprobe" ] && chmod 4755 "$DESTDIR/usr/bin/nvidia-modprobe"

    # ---- prime-run helper (PRIME offload wrapper) --------------------------
    # Shipped by every modern Linux NVIDIA package (Arch's nvidia-prime,
    # Fedora's nvidia-prime, Debian's nvidia-prime-applet wrap the same
    # env-var pattern). Convenience for hybrid-graphics users.
    cat > "$DESTDIR/usr/bin/prime-run" <<'EOF'
#!/bin/sh
# prime-run — launch a command with PRIME offload to NVIDIA GPU
# Shipped by extra/nvidia. Routes OpenGL + Vulkan calls to NVIDIA via
# libglvnd dispatch while the iGPU still drives the display.
exec env \
    __NV_PRIME_RENDER_OFFLOAD=1 \
    __GLX_VENDOR_LIBRARY_NAME=nvidia \
    __VK_LAYER_NV_optimus=NVIDIA_only \
    __NV_PRIME_RENDER_OFFLOAD_PROVIDER=NVIDIA-G0 \
    "$@"
EOF
    chmod 755 "$DESTDIR/usr/bin/prime-run"

    # ---- libglvnd dispatch registry ---------------------------------------
    # These JSON files register NVIDIA's libGLX_nvidia + libEGL_nvidia as
    # vendor providers visible to libglvnd's dispatch layer. Without these,
    # apps that load libglvnd's libGLX.so.0 / libEGL.so.0 won't find the
    # NVIDIA provider even though the .so files are installed.
    install -d -m 755 "$DESTDIR/usr/share/glvnd/egl_vendor.d"
    install -d -m 755 "$DESTDIR/usr/share/glvnd/glx_vendor.d"
    if [ -f "$NV_RUN_SRC/10_nvidia.json" ]; then
        install -m 644 "$NV_RUN_SRC/10_nvidia.json" \
            "$DESTDIR/usr/share/glvnd/egl_vendor.d/10_nvidia.json"
    fi
    if [ -f "$NV_RUN_SRC/10_nvidia_glx.json" ]; then
        install -m 644 "$NV_RUN_SRC/10_nvidia_glx.json" \
            "$DESTDIR/usr/share/glvnd/glx_vendor.d/10_nvidia.json"
    fi

    # ---- Vulkan ICD registry ----------------------------------------------
    install -d -m 755 "$DESTDIR/usr/share/vulkan/icd.d"
    install -d -m 755 "$DESTDIR/usr/share/vulkan/implicit_layer.d"
    if [ -f "$NV_RUN_SRC/nvidia_icd.json" ]; then
        install -m 644 "$NV_RUN_SRC/nvidia_icd.json" \
            "$DESTDIR/usr/share/vulkan/icd.d/nvidia_icd.json"
    fi
    if [ -f "$NV_RUN_SRC/nvidia_layers.json" ]; then
        install -m 644 "$NV_RUN_SRC/nvidia_layers.json" \
            "$DESTDIR/usr/share/vulkan/implicit_layer.d/nvidia_layers.json"
    fi

    # ---- kernel cmdline fragment + modprobe.d nouveau-blacklist ----------
    # Per Prime Directive (operator-direct 2026-05-28): module options that
    # affect boot behavior live on the kernel cmdline so users can audit
    # every load-bearing flag at `cat /proc/cmdline` — the most discoverable
    # single source of truth. linux-kernel/hooks/post-install.sh reads
    # /etc/kernel/cmdline.d/*.conf fragments at UKI rebuild time and embeds
    # them in the signed .cmdline section.
    #
    # Cross-distro cite: Arch + Fedora + Debian all ship these as modprobe
    # options under /etc/modprobe.d/. We deliberately diverge for PD
    # alignment — modprobe.d hides where load-bearing settings live unless
    # the user knows to look, which is exactly the convention PD calls out
    # ("regardless of how conventional it may be").
    install -d -m 755 "$DESTDIR/etc/kernel/cmdline.d"
    cat > "$DESTDIR/etc/kernel/cmdline.d/40-nvidia.conf" <<'EOF'
# Shipped by extra/nvidia — InterGenOS NVIDIA package
#
# Required for Wayland (KMS) + Linux 6.11+ (fbdev hard requirement).
# Kernel 6.18.10 ships in InterGenOS so fbdev=1 is non-negotiable.
#
# These flags appear at `cat /proc/cmdline` at runtime — auditable at
# the most obvious place. The UKI .cmdline section is signed end-to-end
# (sbsigntools chain) so unauthorized cmdline edits are detected at boot.
nvidia-drm.modeset=1 nvidia-drm.fbdev=1
EOF

    # Block nouveau — module BLACKLIST not kernel cmdline. modprobe.d is the
    # correct layer for module load-time policy (the kernel itself doesn't
    # consume blacklist directives — modprobe + systemd-modules-load do).
    # Two-line pattern (blacklist + modeset=0) is belt-and-suspenders:
    # blacklist handles the late-load path (modprobe / systemd-modules-load);
    # modeset=0 handles the early-KMS auto-detection path that bypasses
    # the blacklist.
    install -d -m 755 "$DESTDIR/etc/modprobe.d"
    cat > "$DESTDIR/etc/modprobe.d/nvidia-nouveau-blacklist.conf" <<'EOF'
# Shipped by extra/nvidia — InterGenOS NVIDIA package
#
# Module-loader blacklist for nouveau (NOT kernel cmdline). The nvidia
# driver's own load-time options (modeset, fbdev) live on the kernel
# cmdline at /etc/kernel/cmdline.d/40-nvidia.conf so users can audit at
# `cat /proc/cmdline`.
blacklist nouveau
options nouveau modeset=0
EOF

    install -d -m 755 "$DESTDIR/usr/lib/udev/rules.d"
    if [ -d "$NV_RUN_SRC/udev" ] || compgen -G "$NV_RUN_SRC"/*-nvidia*.rules > /dev/null; then
        # NVIDIA's .run ships udev rules at different paths across versions.
        # Probe both layouts.
        for rule in "$NV_RUN_SRC"/udev/*.rules "$NV_RUN_SRC"/*-nvidia*.rules; do
            [ -f "$rule" ] || continue
            install -m 644 "$rule" "$DESTDIR/usr/lib/udev/rules.d/$(basename "$rule")"
        done
    fi

    install -d -m 755 "$DESTDIR/usr/share/X11/xorg.conf.d"
    if [ -f "$NV_RUN_SRC/10-nvidia-drm-outputclass.conf" ]; then
        install -m 644 "$NV_RUN_SRC/10-nvidia-drm-outputclass.conf" \
            "$DESTDIR/usr/share/X11/xorg.conf.d/10-nvidia-drm-outputclass.conf"
    fi

    # Wayland environment defaults. System-wide GBM backend + GLX vendor
    # selection. Hybrid users can comment these out for iGPU-default
    # + PRIME-on-demand behavior. Documented in HYBRID-GRAPHICS.md.
    install -d -m 755 "$DESTDIR/etc/environment.d"
    cat > "$DESTDIR/etc/environment.d/91-nvidia-wayland.conf" <<'EOF'
# Shipped by extra/nvidia — InterGenOS NVIDIA package
#
# Routes the Wayland compositor + EGL apps to NVIDIA's GBM backend +
# libGLX vendor. Discrete-GPU systems: correct default. Hybrid-laptop
# systems that want iGPU-default + PRIME-on-demand: comment these out
# and use `prime-run` (also shipped) for per-app NVIDIA offload.
GBM_BACKEND=nvidia-drm
__GLX_VENDOR_LIBRARY_NAME=nvidia
EOF

    # ---- systemd units ----------------------------------------------------
    # Suspend/resume/hibernate ship ENABLED via the [Install] section's
    # WantedBy=sleep.target — the installation tree creates the
    # /usr/lib/systemd/system/sleep.target.wants/ symlinks so the units
    # activate on the next sleep transition without operator opt-in.
    # nvidia-persistenced ships DISABLED — no [Install]-wanted symlink
    # is created. Operator opts in via `systemctl enable nvidia-persistenced`.
    install -d -m 755 "$DESTDIR/usr/lib/systemd/system"
    install -d -m 755 "$DESTDIR/usr/lib/systemd/system/sleep.target.wants"
    for unit in nvidia-persistenced.service nvidia-suspend.service \
                nvidia-resume.service nvidia-hibernate.service; do
        if [ -f "$NV_RUN_SRC/systemd/$unit" ]; then
            install -m 644 "$NV_RUN_SRC/systemd/$unit" \
                "$DESTDIR/usr/lib/systemd/system/$unit"
        elif [ -f "$NV_RUN_SRC/$unit" ]; then
            install -m 644 "$NV_RUN_SRC/$unit" \
                "$DESTDIR/usr/lib/systemd/system/$unit"
        fi
    done
    # Auto-enable suspend/resume/hibernate via WantedBy symlinks.
    # nvidia-persistenced INTENTIONALLY excluded — Holy Grail filter.
    for unit in nvidia-suspend nvidia-hibernate; do
        if [ -f "$DESTDIR/usr/lib/systemd/system/${unit}.service" ]; then
            ln -sf "../${unit}.service" \
                "$DESTDIR/usr/lib/systemd/system/sleep.target.wants/${unit}.service"
        fi
    done
    # nvidia-resume hooks systemd-suspend.service + systemd-hibernate.service
    # post-resume; if NVIDIA ships the unit, wire the WantedBy symlinks.
    if [ -f "$DESTDIR/usr/lib/systemd/system/nvidia-resume.service" ]; then
        install -d -m 755 "$DESTDIR/usr/lib/systemd/system/systemd-suspend.service.wants"
        install -d -m 755 "$DESTDIR/usr/lib/systemd/system/systemd-hibernate.service.wants"
        ln -sf "../nvidia-resume.service" \
            "$DESTDIR/usr/lib/systemd/system/systemd-suspend.service.wants/nvidia-resume.service"
        ln -sf "../nvidia-resume.service" \
            "$DESTDIR/usr/lib/systemd/system/systemd-hibernate.service.wants/nvidia-resume.service"
    fi

    # ---- sysusers.d for nvidia-persistenced -------------------------------
    # systemd-sysusers creates the system user at first boot. The daemon
    # runs as this user (not root) to hold /dev/nvidiactl without root.
    install -d -m 755 "$DESTDIR/usr/lib/sysusers.d"
    cat > "$DESTDIR/usr/lib/sysusers.d/nvidia-persistenced.conf" <<'EOF'
# Shipped by extra/nvidia — InterGenOS NVIDIA package
u nvidia-persistenced - "NVIDIA Persistence Daemon" /
EOF

    # ---- pkm runtime hooks (post-install + rebuild + sign + check-hw) -----
    install -d -m 755 "$DESTDIR/var/lib/pkm/hooks/nvidia"
    install -m 755 "$BUILD_DIR/hooks/post-install.sh" \
        "$DESTDIR/var/lib/pkm/hooks/nvidia/post-install"
    install -m 755 "$BUILD_DIR/hooks/rebuild-modules.sh" \
        "$DESTDIR/var/lib/pkm/hooks/nvidia/rebuild-modules"
    install -m 755 "$BUILD_DIR/hooks/sign-module.sh" \
        "$DESTDIR/var/lib/pkm/hooks/nvidia/sign-module.sh"
    install -m 755 "$BUILD_DIR/hooks/check-hardware.sh" \
        "$DESTDIR/var/lib/pkm/hooks/nvidia/check-hardware.sh"
    install -m 755 "$BUILD_DIR/hooks/pre-remove.sh" \
        "$DESTDIR/var/lib/pkm/hooks/nvidia/pre-remove"

    # ---- EULA install-helper (hybrid-model, 2026-05-28) -------------------
    # pkm runs /usr/lib/intergen/eula-helpers/nvidia-eula BEFORE the
    # nvidia package install proceeds. The helper is a prompt_toolkit
    # full-screen pager that fetches the CURRENT NVIDIA EULA from
    # download.nvidia.com, presents it with ACCEPT/DECLINE buttons,
    # and writes the acceptance marker + verbatim transcript at
    # /var/lib/intergen/eula/ on ACCEPT. See nvidia-eula.py for the
    # canonical implementation + docs/operations/eula-helper-flow.md
    # for the end-to-end flow + exit-code contract.
    install -d -m 755 "$DESTDIR/usr/lib/intergen/eula-helpers"
    install -m 755 "$BUILD_DIR/eula-helper/nvidia-eula.py" \
        "$DESTDIR/usr/lib/intergen/eula-helpers/nvidia-eula"
    # The banner asset sits alongside the helper executable. The helper
    # resolves it via Path(__file__).resolve().parent so install location
    # must place banner.txt in the same dir as the executable.
    install -m 644 "$BUILD_DIR/eula-helper/banner.txt" \
        "$DESTDIR/usr/lib/intergen/eula-helpers/banner.txt"

    # Marker + transcript directory (mode 0o755 root:root). The helper's
    # write_marker_and_transcript will mkdir(parents=True, exist_ok=True)
    # too — this is just the build-time pre-creation so the directory is
    # owned by this package (and pkm verify sees it).
    install -d -m 755 "$DESTDIR/var/lib/intergen/eula"

    # ---- Documentation ----------------------------------------------------
    install -d -m 755 "$DESTDIR/usr/share/doc/nvidia"
    install -m 644 "$BUILD_DIR/docs/HYBRID-GRAPHICS.md" \
        "$DESTDIR/usr/share/doc/nvidia/HYBRID-GRAPHICS.md"
    install -m 644 "$BUILD_DIR/docs/MODPROBE-OPTIONS.md" \
        "$DESTDIR/usr/share/doc/nvidia/MODPROBE-OPTIONS.md"
    install -m 644 "$BUILD_DIR/docs/SIGNING-CHAIN.md" \
        "$DESTDIR/usr/share/doc/nvidia/SIGNING-CHAIN.md"

    # Clean up scratch files
    rm -f /tmp/.nvidia-build-open-src /tmp/.nvidia-build-run-src
}

post_install() {
    set -e
    # This runs at PACKAGE BUILD time in the chroot. Nothing to do here —
    # the user-install-time work happens in /var/lib/pkm/hooks/nvidia/post-install
    # which pkm fires after archive deploy (per pkm/installer.py:854).
    :
}
