#!/bin/bash

# omarchy:summary=Set the Plymouth boot theme colors and logo
# omarchy:args=<background-hex> <text-hex> <path-to-logo.png>
# omarchy:examples=omarchy plymouth set '#1d2021' '#ebdbb2' ~/.config/omarchy/current/theme/plymouth/logo.png
# omarchy:requires-sudo=true

# Configure the Plymouth boot theme with a custom background color, text color, and logo.
# Stages the change in a temp dir, then commits the staged files to /usr/share and
# rebuilds the initramfs. Also syncs the SDDM login screen (the post-logout
# screen) with the same colors and logo so boot/login stay visually unified.

if [[ $# -ne 3 ]]; then
  echo "Usage: omarchy-plymouth-set <background-hex> <text-hex> <path-to-logo.png>" >&2
  exit 1
fi

bg_hex="${1#\#}"
text_hex="${2#\#}"
logo_path="$3"

if ! [[ $bg_hex =~ ^[0-9a-fA-F]{6}$ ]]; then
  echo "Invalid background color: $1 (expected #RRGGBB)" >&2
  exit 1
fi

if ! [[ $text_hex =~ ^[0-9a-fA-F]{6}$ ]]; then
  echo "Invalid text color: $2 (expected #RRGGBB)" >&2
  exit 1
fi

if [[ ! -f $logo_path ]]; then
  echo "Logo file not found: $logo_path" >&2
  exit 1
fi

bg_r=$(awk -v n=$((16#${bg_hex:0:2})) 'BEGIN{printf "%.3f", n/255}')
bg_g=$(awk -v n=$((16#${bg_hex:2:2})) 'BEGIN{printf "%.3f", n/255}')
bg_b=$(awk -v n=$((16#${bg_hex:4:2})) 'BEGIN{printf "%.3f", n/255}')

theme_dir="/usr/share/plymouth/themes/omarchy"
staging_dir=$(mktemp -d)
trap 'rm -rf "$staging_dir"' EXIT

find ~/.local/share/omarchy/default/plymouth -maxdepth 1 -type f -exec cp -t "$staging_dir/" {} +
cp "$logo_path" "$staging_dir/logo.png"

sed -i \
  -e "s/^Window.SetBackgroundTopColor.*/Window.SetBackgroundTopColor($bg_r, $bg_g, $bg_b);/" \
  -e "s/^Window.SetBackgroundBottomColor.*/Window.SetBackgroundBottomColor($bg_r, $bg_g, $bg_b);/" \
  "$staging_dir/omarchy.script"

for asset in bullet.png entry.png lock.png progress_bar.png; do
  magick "$staging_dir/$asset" -channel RGB +level-colors "#$text_hex","#$text_hex" "$staging_dir/$asset"
done

sudo cp -a "$staging_dir/." "$theme_dir/"
sudo plymouth-set-default-theme omarchy

if omarchy-cmd-present limine-mkinitcpio; then
  sudo limine-mkinitcpio
else
  sudo mkinitcpio -P
fi

# Sync the SDDM login screen with the same colors and logo.
sddm_dir="/usr/share/sddm/themes/omarchy"
sddm_template="$HOME/.local/share/omarchy/default/sddm/omarchy/Main.qml"

sed \
  -e "s/#1a1b26/#$bg_hex/g" \
  -e "s/#ffffff/#$text_hex/g" \
  "$sddm_template" | sudo tee "$sddm_dir/Main.qml" >/dev/null

sudo cp "$logo_path" "$sddm_dir/logo.png"
for asset in bullet.png entry.png lock.png; do
  sudo cp "$staging_dir/$asset" "$sddm_dir/$asset"
done
for asset in entry lock; do
  magick "$staging_dir/$asset.png" -channel RGB +level-colors "#f7768e","#f7768e" "$staging_dir/$asset-failed.png"
  sudo cp "$staging_dir/$asset-failed.png" "$sddm_dir/$asset-failed.png"
done
sudo rm -f "$sddm_dir/logo.svg"
