#!/bin/bash
# Switches the ML4W/Hyprland wallpaper on the target host (the VM, or an
# already-themed local laptop with --local) and lets matugen regenerate
# the whole color theme (waybar, kitty, rofi, gtk, btop, swaync, quickshell,
# pywalfox, ...) from the new image's dominant color.
#
# Wallpapers live in ~/.config/ml4w/wallpapers on the target host (that's
# the folder ~/.config/ml4w/settings/wallpaper-folder points at). The
# actual work is done by ~/.config/ml4w/scripts/ml4w-wallpaper there.
#
# A plain non-interactive `ssh host cmd` does NOT inherit the Wayland/Hyprland
# session's environment (WAYLAND_DISPLAY, XDG_RUNTIME_DIR,
# HYPRLAND_INSTANCE_SIGNATURE) -- without those, `awww query` and `hyprctl`
# hang forever waiting for a compositor socket that (as far as that shell
# knows) doesn't exist. So we discover the running session's signature and
# socket name from /run/user/$UID/hypr and /run/user/$UID/wayland-* on the
# target host and export them explicitly before calling ml4w-wallpaper.
# (With --local this is run directly in the caller's own shell, but the
# same discovery is still needed since a script invocation doesn't
# necessarily inherit the login session's environment either.)
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

parse_target_flag "$@"
set -- "${PARSED_ARGS[@]+"${PARSED_ARGS[@]}"}"

WALLPAPER_DIR_REMOTE='$HOME/.config/ml4w/wallpapers'

usage() {
    echo "Usage: $0 [--vm|--local] [wallpaper-name]"
    echo "  --vm (default): act on the libvirt VM over SSH."
    echo "  --local: act on the local machine directly."
    echo "  Run with no wallpaper-name to pick from a list."
    echo "  wallpaper-name can be given with or without its extension."
}

# --- 1. Fetch the list of available wallpapers from the target host ---
mapfile -t WALLPAPERS < <(
    run "find ${WALLPAPER_DIR_REMOTE} -maxdepth 1 -type f \
            \( -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.png' -o -iname '*.webp' -o -iname '*.gif' \) \
            -printf '%f\n'" | sort
)

if [ "${#WALLPAPERS[@]}" -eq 0 ]; then
    echo "No wallpapers found in ${WALLPAPER_DIR_REMOTE} (target: ${TARGET})." >&2
    exit 1
fi

# --- 2. Pick a wallpaper: from $1, or interactively ---
CHOICE="${1:-}"

if [ -z "$CHOICE" ]; then
    echo "Available wallpapers:"
    select name in "${WALLPAPERS[@]}"; do
        if [ -n "${name:-}" ]; then
            CHOICE="$name"
            break
        fi
        echo "Invalid selection, try again."
    done
else
    # Allow passing the name with or without extension, case-insensitively.
    MATCH=""
    for w in "${WALLPAPERS[@]}"; do
        base="${w%.*}"
        if [ "${w,,}" = "${CHOICE,,}" ] || [ "${base,,}" = "${CHOICE,,}" ]; then
            MATCH="$w"
            break
        fi
    done
    if [ -z "$MATCH" ]; then
        echo "No wallpaper matching '${CHOICE}'." >&2
        echo "Available: ${WALLPAPERS[*]}" >&2
        exit 1
    fi
    CHOICE="$MATCH"
fi

echo ">>> Setting wallpaper: ${CHOICE} (target: ${TARGET})"

# --- 3. Apply it, with the live Hyprland session's env injected ---
run_script "$CHOICE" <<'REMOTE'
set -euo pipefail
CHOICE="$1"
RUNTIME_DIR="/run/user/$(id -u)"

SIG=$(ls "$RUNTIME_DIR/hypr" 2>/dev/null | head -n1)
SOCK=$(ls "$RUNTIME_DIR" 2>/dev/null | grep -E '^wayland-[0-9]+$' | head -n1)

if [ -z "$SIG" ] || [ -z "$SOCK" ]; then
    echo "No running Hyprland session found (nothing under ${RUNTIME_DIR}/hypr)." >&2
    exit 1
fi

export XDG_RUNTIME_DIR="$RUNTIME_DIR"
export WAYLAND_DISPLAY="$SOCK"
export HYPRLAND_INSTANCE_SIGNATURE="$SIG"

exec "$HOME/.config/ml4w/scripts/ml4w-wallpaper" "$HOME/.config/ml4w/wallpapers/$CHOICE" --notifications
REMOTE

# --- 4. Re-tint the adapted app/tray icons (duotone is the active method
#        -- see 14-generate-duotone-icons.sh) to the accent color matugen
#        just regenerated ----------------------------------------------
echo ">>> Re-tinting adapted app icons to the new accent color"
./15-deploy-duotone-theme.sh "--${TARGET}"
