#!/bin/bash

# omarchy:summary=Preview a Plymouth boot screen with custom colors and logo
# omarchy:args=<background-hex> <text-hex> <path-to-logo.png> <output-path>
# omarchy:examples=omarchy plymouth preview '#1d2021' '#ebdbb2' ~/.local/state/omarchy/current/theme/plymouth/logo.png /tmp/plymouth-preview.png

# Render a Plymouth login-screen preview PNG by compositing the staged omarchy
# theme assets (recolored with the given text color) onto the background.

if (( $# != 4 )); then
  echo "Usage: omarchy-plymouth-preview <background-hex> <text-hex> <path-to-logo.png> <output-path>" >&2
  exit 1
fi

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

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

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

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

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

canvas_w=1920
canvas_h=1080

logo_w=$(magick identify -format '%w' "$staging_dir/logo.png")
logo_h=$(magick identify -format '%h' "$staging_dir/logo.png")
entry_w=$(magick identify -format '%w' "$staging_dir/entry.png")
entry_h=$(magick identify -format '%h' "$staging_dir/entry.png")
lock_h=$(awk "BEGIN{print int($entry_h * 0.8)}")
lock_w=$(awk "BEGIN{print int(84 * $lock_h / 96)}")

logo_x=$(( (canvas_w - logo_w) / 2 ))
logo_y=$(( (canvas_h - logo_h) / 2 ))
entry_x=$(( (canvas_w - entry_w) / 2 ))
entry_y=$(( logo_y + logo_h + 40 ))
lock_x=$(( entry_x - lock_w - 15 ))
lock_y=$(( entry_y + entry_h/2 - lock_h/2 ))
bullet_y=$(( entry_y + entry_h/2 - 4 ))

bullet_args=()
for i in 0 1 2 3; do
  bx=$(( entry_x + 20 + i * 12 ))
  bullet_args+=( '(' "$staging_dir/bullet.png" -resize 7x7 ')' -geometry +${bx}+${bullet_y} -composite )
done

magick -size ${canvas_w}x${canvas_h} "xc:#$bg_hex" \
  "$staging_dir/logo.png" -geometry +${logo_x}+${logo_y} -composite \
  "$staging_dir/entry.png" -geometry +${entry_x}+${entry_y} -composite \
  \( "$staging_dir/lock.png" -resize ${lock_w}x${lock_h} \) -geometry +${lock_x}+${lock_y} -composite \
  "${bullet_args[@]}" \
  "$output_path"

imv -f "$output_path"
