#!/bin/bash
# Installs the duotone icon set cached in generated_icons/duotone/ onto the
# target host, colorized by the target's CURRENT matugen palette (dark
# stop: primary_container, light stop: on_primary_container by default --
# see ~/.config/ml4w/colors/colors.json, regenerated on every wallpaper
# switch). Counterpart to 11-deploy-icon-theme.sh, for the duotone method
# instead of the flat-silhouette one -- see 14-generate-duotone-icons.sh
# and lib/icon_duotone_deploy.py for how the masters were built/colorized.
#
# Same safety net as 11: any pre-existing file at an install destination is
# backed up (once) to ~/.config/timhyperland-icons/original-icons-backup/
# before being overwritten -- see 11's header comment for why that matters
# (icons can resolve through a theme, e.g. kora here, whose only copy is
# itself user-local, not a protected system file).
#
# Restarts Quickshell (dock/status bar/overview) at the end, same mechanism
# as 11, so the result is visible immediately -- via ml4w-autostart, which
# ALSO re-applies the current wallpaper's theming on its own
# ($HOME/.config/ml4w/scripts/ml4w-autostart calls "ml4w-wallpaper $(cat
# $CACHE_FILE) --skip-wallpaper" as part of its normal startup sync). If
# 19-hook-icon-retint-into-wallpaper-app.sh's hook is installed, THAT
# invocation runs straight back into this same script -- restart
# Quickshell -> re-run ml4w-autostart -> re-apply wallpaper -> hook fires
# -> restart Quickshell -> ... an infinite loop, discovered the hard way
# (each cycle costs a real matugen+176-icon recolor pass, so this isn't a
# cheap no-op loop). TIMHYPERLAND_ICON_RETINT_IN_PROGRESS below is the
# re-entrancy guard that breaks it: exported right before launching
# ml4w-autostart, inherited by the ml4w-wallpaper it spawns and by the
# hook's own call to this script inside that, so this script exits
# immediately on that re-entrant call instead of restarting Quickshell a
# second time.
#
# Usage: 15-deploy-duotone-theme.sh [--vm|--local] [--dark-stop KEY] [--light-stop KEY]
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

if [ -n "${TIMHYPERLAND_ICON_RETINT_IN_PROGRESS:-}" ]; then
    echo ">>> Re-entered via ml4w-autostart's own wallpaper resync -- already" >&2
    echo "    retinted this cycle, skipping to avoid an infinite loop." >&2
    exit 0
fi

DARK_STOP="primary_container"
LIGHT_STOP="on_primary_container"
parse_target_flag "$@"
set -- "${PARSED_ARGS[@]+"${PARSED_ARGS[@]}"}"
while [ $# -gt 0 ]; do
    case "$1" in
        --dark-stop) shift; DARK_STOP="$1" ;;
        --light-stop) shift; LIGHT_STOP="$1" ;;
        *) echo "Unknown argument: $1" >&2; exit 1 ;;
    esac
    shift
done

GEN_DIR="../generated_icons"
RASTER_DIR="${GEN_DIR}/duotone"
VECTOR_DIR="${GEN_DIR}/duotone_vector"
MANIFEST="${GEN_DIR}/manifest.json"

HAS_VECTOR=$([ -d "$VECTOR_DIR" ] && [ -n "$(ls -A "$VECTOR_DIR" 2>/dev/null)" ] && echo 1 || echo 0)
HAS_RASTER=$([ -d "$RASTER_DIR" ] && [ -n "$(ls -A "$RASTER_DIR" 2>/dev/null)" ] && echo 1 || echo 0)
if [ "$HAS_VECTOR" = 0 ] && [ "$HAS_RASTER" = 0 ]; then
    echo "No generated duotone icons in ${VECTOR_DIR} or ${RASTER_DIR} -- run ./14-generate-duotone-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 palette from the target"
run "cat ${COLORS_PATH_REMOTE}" > "${WORK}/colors.json"

echo ">>> [2/4] Colorizing (dark=${DARK_STOP}, light=${LIGHT_STOP}) and staging locally"
python3 ./lib/icon_duotone_deploy.py \
    --vector-dir "$VECTOR_DIR" \
    --raster-dir "$RASTER_DIR" \
    --manifest "$MANIFEST" \
    --colors "${WORK}/colors.json" \
    --staging-dir "${WORK}/staging" \
    --dark-stop "$DARK_STOP" \
    --light-stop "$LIGHT_STOP"

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"
export TIMHYPERLAND_ICON_RETINT_IN_PROGRESS=1
~/.config/ml4w/scripts/ml4w-autostart >/dev/null 2>&1 &
disown
REMOTE

echo ">>> Done."
