#!/bin/bash
# Installs the icon set cached in generated_icons/silhouettes/ onto the
# target host, stamped with its CURRENT accent color
# (~/.config/ml4w/colors/colors.json's "primary", regenerated by matugen on
# every wallpaper switch -- see 06-switch-wallpaper.sh, which calls this
# script automatically after each switch).
#
# All the real work (fetching the accent color, substituting it into the
# cached silhouettes, rendering the raster mirrors) happens on THIS HOST;
# the target only needs `tar`/`base64` to receive the result, pushed in one
# shot into ~/.local/share/icons/{hicolor,breeze-dark}/{scalable,48x48,64x64,
# 128x128}/{apps,status}/ -- both configured theme names on this setup
# (GTK's "kora", rofi's hardcoded "Tela-circle-dracula") turn out not to be
# installed at all, so lookups bottom out on hicolor in practice, except
# for Qt apps that go through qt6ct's own icon_theme (breeze-dark here)
# instead; installing into both covers either path. That also means this
# script is the one to run, with no potrace/tracing step at all, to light
# up the same icon set on a brand-new CachyOS install that already has this
# repo's generated_icons/ committed.
#
# SAFETY: before overwriting anything, any pre-existing file at the install
# destination is backed up (once) to ~/.config/timhyperland-icons/
# original-icons-backup/. This matters because icons can resolve through a
# theme whose "system" copy doesn't actually exist (e.g. kora here -- see
# icon_remote.py's build_theme_chain) -- in that case the only copy IS the
# user-local one, and overwriting it in place with no backup would destroy
# the real icon theme's own art permanently. hicolor/breeze-dark overrides
# never hit this (their real copies are root-owned under /usr/share, left
# untouched), but any theme resolved from $HOME/.local/share/icons could.
#
# Finally restarts the live Quickshell session (dock, status bar, overview)
# via ~/.config/ml4w/scripts/ml4w-autostart -- rofi/Walker re-scan the icon
# theme fresh on every launch so they don't need this, but the dock/bar/
# overview are long-running processes that may have already cached the old
# icon lookups in memory; new files on disk alone won't repaint them. That
# script is ML4W's own sanctioned restart path (its own comment: "a manual
# run of this script still themes the dock icons"), already idempotent/safe
# to rerun -- it guards the one genuinely first-run-only step (the welcome
# window) behind ~/.cache/ml4w-welcome-autostart. Skipped gracefully (not a
# hard failure) if no Hyprland session is currently running on the target.
#
# Usage: 11-deploy-icon-theme.sh [--vm|--local]
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

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

GEN_DIR="../generated_icons"
SILHOUETTE_DIR="${GEN_DIR}/silhouettes"
MANIFEST="${GEN_DIR}/manifest.json"

if [ ! -d "$SILHOUETTE_DIR" ] || [ -z "$(ls -A "$SILHOUETTE_DIR" 2>/dev/null)" ]; then
    echo "No generated icons in ${SILHOUETTE_DIR} -- run ./10-generate-app-icons.sh first." >&2
    exit 1
fi

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

echo ">>> Target: ${TARGET}"

COLORS_PATH_REMOTE='$HOME/.config/ml4w/colors/colors.json'
echo ">>> [1/4] Fetching current accent color from the target"
run "cat ${COLORS_PATH_REMOTE}" > "${WORK}/colors.json"

echo ">>> [2/4] Staging icons locally with the current accent"
python3 ./lib/icon_deploy.py \
    --silhouette-dir "$SILHOUETTE_DIR" \
    --manifest "$MANIFEST" \
    --colors "${WORK}/colors.json" \
    --staging-dir "${WORK}/staging"

echo ">>> [3/4] Installing (backing up any pre-existing file before its first overwrite)"
tar -C "${WORK}/staging" -cf - . | base64 -w0 > "${WORK}/staging.tar.b64"
STAGING_B64_REMOTE='$HOME/.config/timhyperland-icons/staging.tar.b64'
run "mkdir -p \$HOME/.config/timhyperland-icons && cat > ${STAGING_B64_REMOTE}" < "${WORK}/staging.tar.b64"

run_script <<'REMOTE'
set -euo pipefail
ICONS_DIR="$HOME/.local/share/icons"
BACKUP_DIR="$HOME/.config/timhyperland-icons/original-icons-backup"
STAGING_B64="$HOME/.config/timhyperland-icons/staging.tar.b64"
TMP_EXTRACT=$(mktemp -d)
trap 'rm -rf "$TMP_EXTRACT"' EXIT

base64 -d < "$STAGING_B64" | tar -C "$TMP_EXTRACT" -xf -
mkdir -p "$ICONS_DIR" "$BACKUP_DIR"

backed_up=0
while IFS= read -r -d '' f; do
    rel="${f#"$TMP_EXTRACT"/}"
    live="$ICONS_DIR/$rel"
    backup="$BACKUP_DIR/$rel"
    if [ -f "$live" ] && [ ! -f "$backup" ]; then
        mkdir -p "$(dirname "$backup")"
        cp "$live" "$backup"
        backed_up=$((backed_up + 1))
    fi
    mkdir -p "$(dirname "$live")"
    cp "$f" "$live"
done < <(find "$TMP_EXTRACT" -type f -print0)

echo "Backed up ${backed_up} pre-existing file(s) before their first overwrite (kept under ${BACKUP_DIR})"
rm -f "$STAGING_B64"
REMOTE

echo ">>> [4/4] Restarting Quickshell (dock/status bar/overview) to pick up the new icons"
run_script <<'REMOTE'
set -euo pipefail
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 -- the icon files are installed and" >&2
    echo "will show up next login/qs restart." >&2
    exit 0
fi
export XDG_RUNTIME_DIR="$RUNTIME_DIR"
export WAYLAND_DISPLAY="$SOCK"
export HYPRLAND_INSTANCE_SIGNATURE="$SIG"
~/.config/ml4w/scripts/ml4w-autostart >/dev/null 2>&1 &
disown
REMOTE

echo ">>> Done."
