#!/bin/bash
# Builds the Omarchy boot splash into the initramfs in place of Plymouth: sway
# drawing with its software renderer through the kernel's KMS driver (there is
# no Mesa or NVIDIA userspace in the image), with Quickshell on Qt Quick's
# software backend for the logo, the unlock prompt and the progress bar.
#
# The scripts it carries (default/splash/) run under the initramfs's busybox
# ash, as mkinitcpio's own runtime hooks do.

build() {
  local source=/usr/share/omarchy/default/splash
  local qt=/usr/lib/qt6 module plugin file script keyboard
  local font=/usr/share/fonts/noto/NotoSansMono-Regular.ttf
  local arrow=/usr/share/icons/Adwaita/cursors/default

  if [[ " ${HOOKS[*]} " == *" plymouth "* ]]; then
    error "omarchy-splash replaces the plymouth hook; remove plymouth from HOOKS"
    return 1
  fi

  # First, so add_binary finds ICU's data library already in the image.
  omarchy_splash_icu_stub
  map add_binary sway seatd seatd-launch quickshell

  # What Qt and Quickshell load at run time, which no ELF dependency names.
  for plugin in platforms/libqwayland.so wayland-shell-integration/libxdg-shell.so; do
    add_binary "$qt/plugins/$plugin"
  done
  for module in QML QtQml QtQml/Models QtQml/WorkerScript QtQuick QtQuick/Shapes \
    Quickshell Quickshell/_Window Quickshell/Io Quickshell/I3 Quickshell/I3/_Ipc Quickshell/Wayland "$qt"/qml/Quickshell/Wayland/_*; do
    module=${module#"$qt/qml/"}
    # The .qmltypes are for tools such as qmllint.
    for file in "$qt/qml/$module"/*; do
      if [[ ! -f $file || $file == *.qmltypes ]]; then
        continue
      elif [[ $file == *.so ]]; then
        add_binary "$file"
      else
        add_file "$file"
      fi
    done
  done

  # The keyboard the unlock prompt types with (layouts), built from
  # vconsole.conf rather than carrying it: a layout that types no Latin
  # letters comes along behind US, where omarchy_vconsole.conf keeps
  # vconsole.conf itself out of the image (#6229). Then the XKB data and the
  # compose tables, as Plymouth's hook carried for its keyboard. libinput also
  # needs input devices tagged as such, and its quirks.
  if ! keyboard=$("$source/layouts" /etc/vconsole.conf); then
    error "omarchy-splash: cannot read the keyboard layout from /etc/vconsole.conf"
    return 1
  fi
  printf '%s\n' "$keyboard" | add_file - /usr/lib/omarchy-splash/vconsole.conf 644
  add_omarchy_splash_dir /usr/share/X11/xkb
  add_omarchy_splash_dir /usr/share/X11/locale
  add_omarchy_splash_dir /usr/share/libinput
  add_udev_rule 60-input-id.rules

  # Hot-pluggable USB pointer drivers the stock keyboard hook omits (stays
  # unfiltered even though omarchy-splash runs after autodetect).
  add_module 'synaptics_usb?'

  # Touchpads and pointers (the keyboard hook brings only USB HID,
  # drivers/hid/hid-* and input/serio|keyboard): I2C HID, Intel THC, PS/2 and
  # I2C mice/touchpads, Synaptics RMI4, the Intel LPSS (and idma64 DMA) and
  # I2C/SMBus controllers they sit on, and Intel pinctrl for their GPIO IRQs.
  # Combine into one pattern so all_modules scans /usr/lib/modules once.
  add_checked_modules \
    '/drivers/(hid/(i2c-hid|intel-thc-hid)/|input/(mouse|rmi4)/|mfd/intel-lpss|dma/idma64|i2c/busses/i2c-(designware|i801|piix4|amd-mp2|qcom-geni)|pinctrl/intel/)'

  # The font a shown password is drawn in (ui/Splash.qml), at its own path.
  if [[ -f $font ]]; then
    add_file "$font"
  else
    warning "omarchy-splash: $font (noto-fonts) is missing; the unlock prompt cannot show the typed password"
  fi
  # The pointer's arrow (sway.conf), at its own path.
  if [[ -f $arrow ]]; then
    add_file "$arrow"
  else
    warning "omarchy-splash: $arrow (adwaita-cursors) is missing; the pointer is drawn unscaled"
  fi

  # Images built without early KMS drivers (such as pre-built generic UKIs)
  # can opt in with OMARCHY_SPLASH_NO_KMS=1 so session draws on simpledrm
  # immediately instead of waiting 8 seconds for a native GPU driver.
  if [[ -n ${OMARCHY_SPLASH_NO_KMS:-} ]]; then
    add_file /dev/null /usr/lib/omarchy-splash/no-kms 644
  fi

  for script in answer plymouth power-button session stop ui-launch; do
    add_file "$source/$script" "/usr/lib/omarchy-splash/$script" 755
  done
  add_symlink /usr/bin/plymouth /usr/lib/omarchy-splash/plymouth
  add_file "$source/sway.conf" /usr/lib/omarchy-splash/sway.conf
  # The login screen shares these files and runs from the real root.
  for file in "$source"/ui/*.qml; do
    [[ $file == */greeter.qml ]] && continue
    add_file "$file" "/usr/lib/omarchy-splash/ui/${file##*/}"
  done

  add_runscript
}

# Bulk-copy a static data directory into $BUILDROOT instead of mkinitcpio's
# add_full_dir, which forks cp once per file (500+ files across xkb, locale
# and libinput). Named add_* so mkinitcpio's RETURN trap counts any copy error
# in _builderrors, and points symlinked directories at their resolved target so
# chained relative symlinks never dangle inside the image.
add_omarchy_splash_dir() {
  local src=$1 real

  [[ -d $src ]] || return 0
  if [[ -z ${BUILDROOT:-} ]]; then
    add_full_dir "$src"
    return
  fi
  if [[ -L $src ]]; then
    real=$(realpath -- "$src") || return
    add_dir "${src%/*}" || return
    add_symlink "$src" "$real" || return
    src=$real
  fi
  add_dir "$src" || return
  if ! command cp -a -- "$src/." "${BUILDROOT}${src}/"; then
    error "omarchy-splash: failed to copy '%s'" "$src"
    # Bash's RETURN trap reads $? from the last command before return, not
    # return's argument, so fail explicitly before returning.
    false
    return
  fi
}

# Qt links ICU, whose data library is 32 MiB of collation, locale and codec
# tables the splash never reads: it runs in the C locale, and Qt draws and
# upper-cases text with its own Unicode tables. An empty data package under the
# same soname, as ICU's own stubdata builds, takes its place (#21107). Without
# gcc (base-devel) the real one comes along instead.
omarchy_splash_icu_stub() {
  local data soname tmp

  data=$(ldd "$(type -P quickshell)" | awk '$1 ~ /^libicudata\.so\.[0-9]+$/ { print $3; exit }')
  [[ $data == /* ]] || return 0
  soname=${data##*/}
  tmp=$(mktemp -d) || { warning "omarchy-splash: no temporary directory; the image carries ICU's full data"; return 0; }

  if icupkg new "$tmp/empty.dat" &&
    genccode -q -a gcc -e "icudt${soname##*.}" -d "$tmp" "$tmp/empty.dat" &&
    gcc -shared -nostdlib -Wl,-soname,"$soname" -o "$tmp/$soname" "$tmp/empty_dat.S"; then
    add_file "$tmp/$soname" "$data" 755
  else
    warning "omarchy-splash: cannot build an empty $soname; the image carries ICU's full data"
  fi
  rm -rf "$tmp"
}

help() {
  cat <<HELPEOF
This hook shows the Omarchy boot splash and drive unlock prompt in place of
Plymouth when the 'splash' kernel parameter is set and 'plymouth.enable=0'
isn't. It replaces the plymouth hook and goes in its place, after udev.
HELPEOF
}
