#!/usr/bin/ash
# Starts the splash: sway on the displays, running the splash's Quickshell
# config and nothing else. The omarchy-splash hook runs this in the background
# and records its pid; it ends when sway does.

run=/run/omarchy-splash

# The GPU's own KMS driver, given up to 8 seconds like plymouthd's
# DeviceTimeout, before settling for the firmware framebuffer (simpledrm,
# efidrm or vesadrm), which the native driver would take away mid-prompt.
#
# sway draws in CPU memory, and every GPU shows a copy of what changed
# (wlroots does that for its software renderer only with a patch; without it,
# only the first GPU's displays light up). The first GPU is the one sway calls
# its own: the firmware's boot display, which is the likeliest to work.
find_cards() {
  native=""
  native_connected=""
  firmware=""
  for card in /sys/class/drm/card*; do
    name=${card##*/}
    case $name in *-*) continue ;; esac
    [ -e "/dev/dri/$name" ] || continue
    # A GPU without display connectors, like a Raspberry Pi's v3d, renders
    # only: it is not the display the wait is for.
    has_connectors "$card" || continue
    # A card whose driver can't be read, as when the firmware framebuffer is
    # being unbound for the GPU's own driver, would otherwise pass for native.
    driver=$(readlink "$card/device/driver") || continue
    case ${driver##*/} in
      simple-framebuffer | efi-framebuffer | vesa-framebuffer)
        firmware=${firmware:+$firmware:}/dev/dri/$name
        continue
        ;;
    esac
    if [ -z "$native_connected" ] && has_connected_output "$card"; then
      native_connected=1
    fi
    if [ "$(cat "$card/device/boot_vga" 2>/dev/null)" = 1 ]; then
      native=/dev/dri/$name${native:+:$native}
    else
      native=${native:+$native:}/dev/dri/$name
    fi
  done
}

has_connectors() {
  for connector in "$1"-*; do
    [ -e "$connector" ] && return 0
  done
  return 1
}

has_connected_output() {
  local status_file status
  for status_file in "$1"-*/status; do
    if IFS= read -r status 2>/dev/null <"$status_file" && [ "$status" = connected ]; then
      return 0
    fi
  done
  return 1
}

# Looks for a GPU every tenth of a second, $1 times at most: there is no file
# watcher in the initramfs. With $2=any (used when a pre-built UKI omits kms),
# a firmware framebuffer settles immediately instead of waiting 8 seconds for a
# native driver that is not in the initramfs. After switch_root, this script's
# root is the emptied initramfs, where neither a GPU nor stopping shows up.
wait_native() {
  i=0
  find_cards
  while [ -z "$native_connected" ] && [ -d "$run" ] && [ ! -e "$run/stopping" ] && [ "$i" -lt "$1" ]; do
    [ "${2:-}" = any ] && [ -n "$firmware" ] && break
    sleep 0.1
    i=$((i + 1))
    find_cards
  done
}

if [ -e /usr/lib/omarchy-splash/no-kms ]; then
  wait_native 80 any
else
  wait_native 80
fi
[ ! -e "$run/stopping" ] || exit 0
selected=${native_connected:+$native}
devices=${selected:-${firmware:-$native}}
if [ -z "$devices" ]; then
  echo "omarchy-splash: no display to draw on"
  exit 1
fi
echo "omarchy-splash: drawing on $devices"
touch "$run/starting"

# amdgpu powers a GPU down once no display is connected to it, and a GPU that
# is powered down misses a display plugged in later. The GPUs stay powered
# while the splash is up; stop hands them back to the kernel.
keep_awake() {
  local ifs=$IFS device control
  [ "$devices" != "$firmware" ] || return 0
  IFS=:
  for device in $devices; do
    control=/sys/class/drm/${device##*/}/device/power/control
    if [ "$(cat "$control" 2>/dev/null)" = auto ] && echo on >"$control"; then
      echo "$control" >>"$run/awake"
    fi
  done
  IFS=$ifs
}
keep_awake

# The keyboard the image was built with (layouts): the XKB settings of
# vconsole.conf, all of them left to libxkbcommon's defaults when it names no
# XKBLAYOUT.
setting() {
  sed -n "s/^$1=//p" /usr/lib/omarchy-splash/vconsole.conf 2>/dev/null
}

# Plymouth starts with the console's Num Lock and Caps Lock.
lit() {
  for led in /sys/class/leds/input*::"$1"/brightness; do
    [ -r "$led" ] && [ "$(cat "$led")" != 0 ] && return 0
  done
  return 1
}

layout=$(setting XKBLAYOUT)
keymap=$(setting KEYMAP)
if [ -z "$layout" ] && [ -n "$keymap" ] && [ "$keymap" != us ] && [ "$keymap" != @kernel ]; then
  # Plymouth read the keys of a console with a KEYMAP but no XKBLAYOUT through
  # the kernel keymap: `plymouth ask-for-password` leaves the password to the
  # console, where the keymap hook loaded it. Setup writes an XKB layout for
  # every keymap it offers, and the splash's migration for the ones older
  # installs lack, so this is a keymap set some other way.
  echo "omarchy-splash: vconsole.conf sets KEYMAP=$keymap but no XKBLAYOUT; the password is asked on the console"
  touch "$run/console-keys"
fi

# The layouts, for the prompt's keyboard to switch between (ui/shell.qml).
export OMARCHY_SPLASH_XKBLAYOUT="$layout" OMARCHY_SPLASH_XKBVARIANT="$(setting XKBVARIANT)"

{
  echo "input type:keyboard {"
  if [ -n "$layout" ]; then
    printf '  xkb_layout "%s"\n' "$layout"
    for pair in model:XKBMODEL variant:XKBVARIANT options:XKBOPTIONS; do
      value=$(setting "${pair#*:}")
      [ -n "$value" ] && printf '  xkb_%s "%s"\n' "${pair%%:*}" "$value"
    done
  fi
  lit numlock && echo "  xkb_numlock enabled"
  lit capslock && echo "  xkb_capslock enabled"
  # The kernel's own autorepeat, which Plymouth's keys came from.
  echo "  repeat_delay 250"
  echo "  repeat_rate 30"
  echo "}"
} >"$run/input.conf"

# wlroots hands each client its keymap through a POSIX shared memory file, and
# the initramfs's /dev has no /dev/shm. stop unmounts it again.
if ! mountpoint -q /dev/shm; then
  mkdir -p /dev/shm
  mount -t tmpfs -o nosuid,nodev,mode=1777 shm /dev/shm && touch "$run/shm"
fi

mkdir -m 0700 -p "$run/runtime" "$run/home"
export XDG_RUNTIME_DIR="$run/runtime"
export HOME="$run/home"
export WLR_RENDERER=pixman
export WLR_DRM_DEVICES="$devices"
export WLR_LIBINPUT_NO_DEVICES=1
export QT_QPA_PLATFORM=wayland
export QT_QUICK_BACKEND=software
export QT_WAYLAND_DISABLE_WINDOWDECORATION=1
# Plymouth composed dead keys with the C locale's table.
unset LANG LC_ALL LC_CTYPE

# omarchy.splash.debug on the kernel command line puts sway's debug log in
# session.log.
debug=""
case " $(cat /proc/cmdline) " in
  *" omarchy.splash.debug "*) debug=--debug ;;
esac

# simpledrm reports no EDID, so sway defaults to scale 1 even on HiDPI panels.
# Pick scale 2 from the framebuffer's shorter side and chassis type while on
# firmware, and record "W H SCALE" for shell/startup-cover.qml so the handoff
# matches only monitors at that mode. Clear both on native KMS.
write_output_conf() {
  local card=${devices%%:*} modes mode="" w="" h="" short=0 chassis="" scale=1
  >"$run/output.conf"
  rm -f /run/omarchy-splash-scale
  [ "$devices" = "$firmware" ] || return 0
  for modes in /sys/class/drm/"${card##*/}"-*/modes; do
    read -r mode 2>/dev/null <"$modes" && [ -n "$mode" ] && break
  done
  case $mode in
    *x*)
      w=${mode%x*}
      h=${mode#*x}
      ;;
    *)
      if read -r mode 2>/dev/null </sys/class/graphics/fb0/virtual_size; then
        case $mode in *,*)
          w=${mode%,*}
          h=${mode#*,}
          ;;
        esac
      fi
      ;;
  esac
  case $w:$h in
    *[!0-9:]* | :* | *:) return 0 ;;
  esac
  if [ "$w" -le "$h" ]; then
    short=$w
  else
    short=$h
  fi
  [ "$short" -gt 0 ] || return 0
  if [ "$short" -ge 2560 ]; then
    scale=2
  elif [ "$short" -gt 1440 ]; then
    read -r chassis 2>/dev/null </sys/class/dmi/id/chassis_type ||
      read -r chassis 2>/dev/null </sys/firmware/devicetree/base/chassis-type || true
    case $chassis in
      8 | 9 | 10 | 11 | 14 | 30 | 31 | 32 | laptop | tablet | convertible | handset)
        scale=2
        ;;
    esac
  fi
  [ "$scale" = 2 ] && echo "output * scale 2" >"$run/output.conf"
  echo "$w $h $scale" >/run/omarchy-splash-scale
  chmod 0644 /run/omarchy-splash-scale
}

# seatd puts the console into graphics mode and turns its keyboard off, so
# keys typed into the prompt never reach the tty behind it.
#
# sway ends with its one client (ui-launch), and the session with sway, but for
# one case: the GPU's own driver binding after the splash settled for the
# firmware framebuffer takes that framebuffer away, and sway with it. The
# splash starts again on the GPU, as Plymouth moves to it, and the new
# Quickshell picks up the pending request. Escape ($run/dismissed) and stop
# ($run/stopping) end it for good.
while :; do
  write_output_conf
  seatd-launch -- sway $debug --config /usr/lib/omarchy-splash/sway.conf
  status=$?
  rm -f "$run/ready"
  if [ -e "$run/stopping" ] || [ -e "$run/dismissed" ] || [ "$devices" != "$firmware" ]; then
    [ -e "$run/dismissed" ] && rm -f /run/omarchy-splash-scale
    exit "$status"
  fi
  wait_native 30
  [ -n "$native_connected" ] || { [ -z "$firmware" ] && [ -n "$native" ]; } || exit "$status"
  # seatd-launch returns before its seatd has let go of the seat, and a second
  # seatd refuses to start while the first's socket is there.
  i=0
  while [ ! -e "$run/stopping" ] && pidof seatd >/dev/null && [ "$i" -lt 30 ]; do
    sleep 0.1
    i=$((i + 1))
  done
  # stop, if it came during those waits, found no sway to end.
  [ ! -e "$run/stopping" ] || exit "$status"
  if pidof seatd >/dev/null; then
    killall -9 seatd
    rm -f /run/seatd.sock
  fi
  devices=$native
  export WLR_DRM_DEVICES="$devices"
  echo "omarchy-splash: the GPU's own driver took the display; drawing on $devices"
  keep_awake
done
