#!/bin/bash

# omarchy:summary=List the kernel's Snapdragon device trees for the UKI
# omarchy:args=[--install]
# omarchy:hidden=true
# omarchy:requires-sudo=true

# systemd-stub picks a device tree from the UKI by SMBIOS identity, out of the
# trees DeviceTreeAuto names. DeviceTreeAuto takes literal paths, so the list
# has to follow the trees the kernel package installs. --install writes the
# list during setup. Without it the command refreshes a list it wrote earlier
# and leaves any other configuration alone, such as the Surface Pro 11's single
# pinned tree. limine runs it that way before every boot image build, from
# /etc/boot/hooks/pre.d, so a kernel update that adds or moves a tree builds
# an image that carries it.

install=0
if [[ ${1:-} == "--install" ]]; then
  install=1
fi

# When invoked as a boot pre-hook, only boot image builds
# (limine-mkinitcpio-install and omarchy-boot-rebuild) need the device tree list
# refreshed. limine-install only copies the EFI loader and limine-snapper-sync
# only updates snapshot entries.
if (( ! install )) && [[ -n ${HOOK_CALLER:-} && $HOOK_CALLER != "limine-mkinitcpio-install" && $HOOK_CALLER != "omarchy-boot-rebuild" ]]; then
  exit 0
fi

managed_begin="# BEGIN OMARCHY QUALCOMM DEVICE TREES"
managed_end="# END OMARCHY QUALCOMM DEVICE TREES"
uki_config=${OMARCHY_QUALCOMM_UKI_CONFIG:-/etc/kernel/uki.conf}
# Each tree is a PE section of its own, and ukify writes every section's header
# into the room the stub reserves. Arch Linux ARM's stub has room for about 119
# trees; systemd-stub-omarchy's is the same release built with room for 1024.
uki_stub=${OMARCHY_QUALCOMM_UKI_STUB:-/usr/lib/systemd-stub-omarchy/linuxaa64.efi.stub}

# Arch Linux ARM's kernel keeps every board's device trees in /boot/dtbs.
# Omarchy's own kernel keeps its Snapdragon ones under its package name, and
# those come first, so the trees match the kernel that boots. linux-omarchy
# itself is named ahead of the pattern, which sorts another kernel's
# linux-omarchy-<name>/qcom before linux-omarchy/qcom.
dtb_root=${OMARCHY_QUALCOMM_DTB_ROOT:-/boot/dtbs}
dtb_dir=$dtb_root/qcom
for kernel_dtb_dir in "$dtb_root"/linux-omarchy/qcom "$dtb_root"/linux-omarchy*/qcom; do
  if [[ -d $kernel_dtb_dir ]]; then
    dtb_dir=$kernel_dtb_dir
    break
  fi
done
dtb_dir=${OMARCHY_QUALCOMM_DTB_DIR:-$dtb_dir}

# The 835, 7c and Snapdragon C laptops are named by maker, so Arch Linux
# ARM's phone and Chromebook trees of those families stay out.
dtbs=()
for dtb in "$dtb_dir"/x1*.dtb "$dtb_dir"/hamoa*.dtb "$dtb_dir"/purwa*.dtb \
  "$dtb_dir"/glymur*.dtb "$dtb_dir"/mahua*.dtb "$dtb_dir"/kalambo*.dtb \
  "$dtb_dir"/sc8280xp*.dtb "$dtb_dir"/sc8180x*.dtb "$dtb_dir"/sdm850*.dtb \
  "$dtb_dir"/msm8998-{asus,hp,lenovo}*.dtb \
  "$dtb_dir"/sc7180-{acer,apcsilmic,ecs,lenovo,samsung,tcl}*.dtb \
  "$dtb_dir"/sc7280-{hp,samsung}*.dtb; do
  if [[ -f $dtb && $dtb != *-el2.dtb ]]; then
    dtbs+=("$dtb")
  fi
done

# An installed machine also gets the tree it runs on as DeviceTree, which
# systemd-stub uses when no tree in the list matches the SMBIOS data. So a
# machine whose hardware IDs systemd-stub doesn't know yet still boots, and
# one whose IDs it knows follows them, also to another tree once an update
# names one. The running device tree's root compatible is that tree's byte
# for byte, so the one file that holds the same list is it. Without a running
# device tree, or without exactly one match, the UKI gets the list alone.
# A tree file holds a property as its token (FDT_PROP = 3), length and name
# offset, then the value, so matching the length too takes only the whole
# property, never a longer list that ends the same way.
own_dtb=""
running_compatible=${OMARCHY_PROC_ROOT:-/proc}/device-tree/compatible
if (( ${#dtbs[@]} > 0 )) && [[ -s $running_compatible ]]; then
  own_dtb=$(python3 - "$running_compatible" "${dtbs[@]}" <<'PY'
import struct
import sys

with open(sys.argv[1], "rb") as f:
    compat = f.read()

if not compat:
    raise SystemExit(0)

header = struct.pack(">II", 3, len(compat))
matches = []
for path in sys.argv[2:]:
    try:
        with open(path, "rb") as f:
            data = f.read()
    except OSError:
        continue
    pos = 0
    while True:
        idx = data.find(compat, pos)
        if idx == -1:
            break
        if idx >= 12 and data[idx - 12:idx - 4] == header:
            matches.append(path)
            break
        pos = idx + 1

if len(matches) == 1:
    print(matches[0])
PY
  )
fi

if (( ! install )) && ! grep -Fqx "$managed_begin" "$uki_config" 2>/dev/null; then
  # Nothing of ours to refresh.
  exit 0
elif (( ${#dtbs[@]} == 0 )); then
  # A kernel without trees keeps the last list rather than an empty one.
  echo "No Windows-on-ARM device trees under $dtb_dir; the UKI gets no .dtbauto sections" >&2
  exit 0
fi

# A boot image build must not stop on this, so any failure leaves the
# configuration as it was and still exits 0. Every write to the copy is
# checked: a full disk must not put a cut-off copy in place of the signing
# settings and paths the configuration holds.
mkdir -p "$(dirname "$uki_config")" || exit 0
uki_tmp=$(mktemp "${uki_config}.XXXXXX") || exit 0

written=1
if [[ -f $uki_config ]]; then
  cp -p "$uki_config" "$uki_tmp" &&
    awk -v begin="$managed_begin" -v end="$managed_end" '
      $0 == begin { managed = 1; next }
      managed && $0 == end { managed = 0; next }
      !managed { print }
    ' "$uki_config" >"$uki_tmp" || written=0
else
  chmod 0644 "$uki_tmp" || written=0
fi

uki_stub_line=""
if [[ -f $uki_stub ]]; then
  uki_stub_line="Stub=$uki_stub"
fi

if (( written )) && [[ -n $own_dtb ]]; then
  printf '%s\n' \
    "$managed_begin" \
    "# Generated by Omarchy for Qualcomm Snapdragon devices." \
    "# systemd-stub selects a device tree from SMBIOS data, and takes this machine's" \
    "# own, matched by its running compatible, when none fits. limine refreshes" \
    "# both before every boot image build (omarchy-update-qualcomm-device-trees)." \
    "[UKI]" \
    ${uki_stub_line:+"$uki_stub_line"} \
    "DeviceTree=$own_dtb" \
    "DeviceTreeAuto=${dtbs[*]}" \
    "$managed_end" >>"$uki_tmp" || written=0
elif (( written )); then
  printf '%s\n' \
    "$managed_begin" \
    "# Generated by Omarchy for Qualcomm Snapdragon devices." \
    "# systemd-stub selects a device tree from SMBIOS data. limine refreshes" \
    "# this list before every boot image build (omarchy-update-qualcomm-device-trees)." \
    "[UKI]" \
    ${uki_stub_line:+"$uki_stub_line"} \
    "DeviceTreeAuto=${dtbs[*]}" \
    "$managed_end" >>"$uki_tmp" || written=0
fi

if (( ! written )); then
  rm -f "$uki_tmp"
  echo "Could not refresh the device tree list in $uki_config; it stays as it was" >&2
elif [[ -f $uki_config ]] && cmp -s "$uki_tmp" "$uki_config"; then
  rm -f "$uki_tmp"
elif mv -f "$uki_tmp" "$uki_config"; then
  # The UKI carries the trees once it is rebuilt. An image's first boot
  # rebuilds after its last step, but does not watch this file.
  if [[ -n ${OMARCHY_IMAGE_BOOT_REBUILD:-} ]]; then
    : >"$OMARCHY_IMAGE_BOOT_REBUILD"
  fi
  if [[ -n $own_dtb ]]; then
    echo "Listed ${#dtbs[@]} device trees in $uki_config, with this machine's own, $own_dtb, to fall back on"
  else
    echo "Listed ${#dtbs[@]} device trees in $uki_config"
  fi
else
  rm -f "$uki_tmp"
fi

exit 0
