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

usage() {
    cat <<'EOF'
Install the NVIDIA headless-display EDID and Xorg configuration.

Usage:
  install-headless-display [--enable] [--connector NAME] [--root DIRECTORY]
  install-headless-display --disable [--root DIRECTORY]
  install-headless-display --prepare [--root DIRECTORY]

Options:
  --connector NAME  NVIDIA display device to configure (default: DFP-0)
  --root DIRECTORY  Target filesystem root for staging/tests (default: /)
  --enable          Install and enable the adaptive headless display (default action)
  --disable         Remove the configuration and disable the boot service
  --prepare         Refresh the Xorg configuration for the current monitor state
  --help            Show this help

The installer detects the NVIDIA PCI BusID with nvidia-xconfig and enables a
boot service. The service uses a physical monitor when one is connected before
the display manager starts, and enables the synthetic display otherwise. The
script does not restart SDDM or remote-access services.
EOF
}

die() {
    printf 'ERROR: %s\n' "$*" >&2
    exit 1
}

ROOT_DIR=${ROOT_DIR:-/}
CONNECTOR=${HEADLESS_CONNECTOR:-DFP-0}
ACTION=enable
ACTION_EXPLICIT=false
CONNECTOR_EXPLICIT=false

select_action() {
    local requested_action=$1

    if [[ "$ACTION_EXPLICIT" == true && "$ACTION" != "$requested_action" ]]; then
        die "action options are mutually exclusive: --$ACTION and --$requested_action"
    fi

    ACTION=$requested_action
    ACTION_EXPLICIT=true
}

while (($# > 0)); do
    case "$1" in
        --connector)
            (($# >= 2)) || die "--connector requires a value"
            CONNECTOR=$2
            CONNECTOR_EXPLICIT=true
            shift 2
            ;;
        --root)
            (($# >= 2)) || die "--root requires a value"
            ROOT_DIR=$2
            shift 2
            ;;
        --enable)
            select_action enable
            shift
            ;;
        --disable)
            select_action disable
            shift
            ;;
        --prepare)
            select_action prepare
            shift
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            die "unknown argument: $1"
            ;;
    esac
done

if [[ "$ROOT_DIR" != "/" ]]; then
    ROOT_DIR=${ROOT_DIR%/}
    [[ -n "$ROOT_DIR" ]] || ROOT_DIR=/
fi

if [[ "$ROOT_DIR" == "/" && ${EUID:-$(id -u)} -ne 0 ]]; then
    die "run as root when installing into /"
fi

TARGET_PREFIX=$ROOT_DIR
[[ "$TARGET_PREFIX" == "/" ]] && TARGET_PREFIX=

EDID_HEX='00ffffffffffff003e149903990300000124010380331d7802ee91a3544c99260f505400000001010101010101010101010101010101023a801871382d40582c4500fd1e1100001e000000fc00484541444c4553532d31303830000000fd00324b1e55110000000000000000000000100000000000000000000000000000007f'
EDID_DIR="$TARGET_PREFIX/etc/X11/edid"
XORG_DIR="$TARGET_PREFIX/etc/X11/xorg.conf.d"
EDID_PATH="$EDID_DIR/headless-1080p.bin"
XORG_PATH="$XORG_DIR/20-headless-display.conf"
STATE_DIR="$TARGET_PREFIX/etc/default"
STATE_PATH="$STATE_DIR/mikado-headless-display"
SERVICE_NAME=mikado-headless-display.service

if [[ "$ACTION" != enable && "$CONNECTOR_EXPLICIT" == true ]]; then
    die "--connector can only be used with --enable"
fi

if [[ "$ACTION" == enable ]]; then
    [[ "$CONNECTOR" =~ ^[[:alnum:]_.-]+$ ]] || die "invalid connector name: $CONNECTOR"
fi

if [[ "$ACTION" == disable ]]; then
    command -v rm >/dev/null 2>&1 || die "required command not found: rm"
    rm -f -- "$XORG_PATH" "$EDID_PATH" "$STATE_PATH"

    if [[ "$ROOT_DIR" == "/" ]] && command -v systemctl >/dev/null 2>&1; then
        if ! systemctl disable "$SERVICE_NAME" >/dev/null; then
            printf 'WARNING: failed to disable %s\n' "$SERVICE_NAME" >&2
        fi
    fi

    printf 'Disabled adaptive headless display configuration\n'
    exit 0
fi

for command_name in awk cmp install mktemp mv od rm wc xxd; do
    command -v "$command_name" >/dev/null 2>&1 || die "required command not found: $command_name"
done

install_atomic() {
    local source_path=$1
    local destination_path=$2
    local mode=$3
    local destination_dir temporary_path

    destination_dir=${destination_path%/*}
    temporary_path=$(mktemp "$destination_dir/.${destination_path##*/}.XXXXXX")
    install -o root -g root -m "$mode" "$source_path" "$temporary_path"
    mv -f "$temporary_path" "$destination_path"
}

read_state_value() {
    local key=$1
    awk -F= -v key="$key" '$1 == key { print substr($0, index($0, "=") + 1) }' "$STATE_PATH"
}

pci_address_for_bus_id() {
    local bus_id=$1
    local bus device function

    IFS=: read -r _ bus device function <<<"$bus_id"
    printf '0000:%02x:%02x.%x' "$bus" "$device" "$function"
}

write_xorg_configuration() {
    local bus_id=$1
    local connector=$2
    local temporary_xorg=$3

    cat >"$temporary_xorg" <<EOF
Section "Device"
    Identifier "NVIDIAHeadless"
    Driver "nvidia"
    BusID "$bus_id"
    Option "AllowEmptyInitialConfiguration" "True"
    Option "ConnectedMonitor" "$connector"
    Option "CustomEDID" "$connector:/etc/X11/edid/headless-1080p.bin"
    Option "UseDisplayDevice" "$connector"
    Option "MetaModes" "$connector: nvidia-auto-select +0+0"
EndSection

Section "Monitor"
    Identifier "HeadlessMonitor"
EndSection

Section "Screen"
    Identifier "HeadlessScreen"
    Device "NVIDIAHeadless"
    Monitor "HeadlessMonitor"
    DefaultDepth 24
    SubSection "Display"
        Depth 24
        Virtual 1920 1080
    EndSubSection
EndSection

Section "ServerLayout"
    Identifier "HeadlessLayout"
    Screen 0 "HeadlessScreen" 0 0
EndSection
EOF
}

prepare_configuration() {
    [[ -r "$STATE_PATH" ]] || die "state file not found: $STATE_PATH"
    [[ -r "$EDID_PATH" ]] || die "EDID file not found: $EDID_PATH"

    local bus_id connector pci_address pci_device_dir
    local drm_root=${HEADLESS_DRM_SYSFS_ROOT:-$TARGET_PREFIX/sys/bus/pci/devices}
    local connector_status connector_edid physical_monitor=false connector_count=0
    local temporary_dir temporary_xorg

    bus_id=$(read_state_value BUS_ID)
    connector=$(read_state_value CONNECTOR)
    [[ "$bus_id" =~ ^PCI:[0-9]+:[0-9]+:[0-9]+$ ]] || die "invalid NVIDIA PCI BusID in $STATE_PATH: $bus_id"
    [[ "$connector" =~ ^[[:alnum:]_.-]+$ ]] || die "invalid connector in $STATE_PATH: $connector"

    pci_address=$(pci_address_for_bus_id "$bus_id")
    pci_device_dir="$drm_root/$pci_address"

    shopt -s nullglob
    for connector_status in "$pci_device_dir"/drm/card*/card*-*/status; do
        ((connector_count += 1))
        [[ $(<"$connector_status") == connected ]] || continue

        connector_edid=${connector_status%/status}/edid
        if [[ -s "$connector_edid" ]] && cmp -s "$connector_edid" "$EDID_PATH"; then
            continue
        fi

        # Some physical DisplayPort monitors report connected before their EDID
        # is readable. The connector state is sufficient to prefer native probing.
        physical_monitor=true
        break
    done
    shopt -u nullglob

    if [[ "$physical_monitor" == true ]]; then
        rm -f -- "$XORG_PATH"
        printf 'Physical monitor detected; using native NVIDIA display detection\n'
        return
    fi

    if ((connector_count == 0)); then
        rm -f -- "$XORG_PATH"
        printf 'WARNING: no NVIDIA DRM connectors found for %s; using native display detection\n' "$bus_id" >&2
        return
    fi

    install -d -o root -g root -m 0755 "$XORG_DIR"
    temporary_dir=$(mktemp -d)
    temporary_xorg="$temporary_dir/20-headless-display.conf"
    write_xorg_configuration "$bus_id" "$connector" "$temporary_xorg"
    install_atomic "$temporary_xorg" "$XORG_PATH" 0644
    rm -rf -- "$temporary_dir"

    printf 'No physical monitor detected; enabled headless display for %s on connector %s\n' "$bus_id" "$connector"
}

if [[ "$ACTION" == prepare ]]; then
    prepare_configuration
    exit 0
fi

NVIDIA_XCONFIG=$(command -v nvidia-xconfig 2>/dev/null || true)
[[ -n "$NVIDIA_XCONFIG" ]] || die "required command not found: nvidia-xconfig"

gpu_info=$("$NVIDIA_XCONFIG" --query-gpu-info 2>&1) || {
    printf '%s\n' "$gpu_info" >&2
    die "nvidia-xconfig --query-gpu-info failed"
}

mapfile -t bus_ids < <(
    awk '
        /PCI BusID[[:space:]]*:/ {
            sub(/^.*PCI BusID[[:space:]]*:[[:space:]]*/, "")
            print
        }
    ' <<<"$gpu_info"
)

if ((${#bus_ids[@]} != 1)); then
    printf '%s\n' "$gpu_info" >&2
    die "expected exactly one NVIDIA PCI BusID, found ${#bus_ids[@]}"
fi

BUS_ID=${bus_ids[0]}
[[ "$BUS_ID" =~ ^PCI:[0-9]+:[0-9]+:[0-9]+$ ]] || die "invalid NVIDIA PCI BusID: $BUS_ID"

temporary_dir=$(mktemp -d)
trap 'rm -rf "$temporary_dir"' EXIT

temporary_edid="$temporary_dir/headless-1080p.bin"
temporary_state="$temporary_dir/mikado-headless-display"

printf '%s' "$EDID_HEX" | xxd -r -p >"$temporary_edid"
edid_size=$(wc -c <"$temporary_edid")
edid_checksum=$(od -An -tu1 -v "$temporary_edid" | awk '{ for (i = 1; i <= NF; i++) sum += $i } END { print sum % 256 }')
[[ "$edid_size" == 128 && "$edid_checksum" == 0 ]] || die "generated EDID failed validation"

cat >"$temporary_state" <<EOF
BUS_ID=$BUS_ID
CONNECTOR=$CONNECTOR
EOF

install -d -o root -g root -m 0755 "$EDID_DIR" "$XORG_DIR" "$STATE_DIR"
install_atomic "$temporary_edid" "$EDID_PATH" 0644
install_atomic "$temporary_state" "$STATE_PATH" 0644
prepare_configuration

if [[ "$ROOT_DIR" == "/" ]] && command -v systemctl >/dev/null 2>&1 \
    && systemctl cat "$SERVICE_NAME" >/dev/null 2>&1; then
    systemctl enable "$SERVICE_NAME" >/dev/null
fi

printf 'Installed adaptive headless display configuration for %s on connector %s\n' "$BUS_ID" "$CONNECTOR"
printf '  %s\n  %s\n  %s\n' "$EDID_PATH" "$STATE_PATH" "$XORG_PATH"
