#!/bin/bash
# Hooks icon re-tinting into ML4W's own wallpaper-apply script
# (~/.config/ml4w/scripts/ml4w-wallpaper) on the TARGET, so a wallpaper
# change made through ML4W's native UI -- the Super+Ctrl+W picker grid
# (quickshell/WallpaperApp/WallpaperWindow.qml), its "Random Wallpaper"
# menu item, the Super+Shift+W keybinding, ml4w-wallpaper-automation --
# re-tints the adapted app/tray icons too, not just
# 06-switch-wallpaper.sh.
#
# Every one of those entry points was confirmed (by reading
# WallpaperWindow.qml and conf/keybindings/default.lua) to funnel
# through this one script, so patching it once covers all of them
# instead of chasing each QML/keybinding call site separately.
#
# This script ONLY edits that one file in place -- it does NOT sync
# scripts/generated_icons (that's 18-deploy-theme-artifacts.sh,
# deliberately kept separate). It expects
# ~/timhyperland/{scripts,generated_icons} to already exist on the
# target and refuses to guess otherwise, and the inserted hook line
# calls ONLY that local copy ($HOME/timhyperland/scripts/15... --local)
# -- never this host, never SSH, never rsync. So once the
# artifacts have been deployed once, both installing/repairing this
# hook and every theme switch afterward work with the target fully
# offline (for --local; for --vm, the only network involved anywhere
# in this script is the SSH connection to the VM needed to edit the
# file at all -- nothing it inserts or runs needs that connection).
#
# Like 07/08, this patches a file owned by the ML4W dotfiles profile,
# which has no custom-override layer -- re-running
# 04-install-ml4w-theme.sh (or an ML4W self-update) silently reverts
# this. Idempotent (a marker comment guards against double-patching)
# and meant to be re-run after any future ML4W (re)install/update --
# that repair never needs network either, since the artifacts it points
# at are already sitting on the target from the last 18 run.
#
# Usage: 19-hook-icon-retint-into-wallpaper-app.sh [--vm|--local]
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
source ./00-config.sh

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

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

echo ">>> [1/2] Checking \$HOME/timhyperland artifacts are already on the target"
if ! run "test -x \$HOME/timhyperland/scripts/15-deploy-duotone-theme.sh && test -f \$HOME/timhyperland/generated_icons/manifest.json" >/dev/null 2>&1; then
    echo "\$HOME/timhyperland/{scripts,generated_icons} not found (or incomplete) on the target." >&2
    echo "Run ./18-deploy-theme-artifacts.sh --${TARGET} first -- that's the one step that" >&2
    echo "needs network to the target; this one and every theme switch afterward don't." >&2
    exit 1
fi

echo ">>> [2/2] Patching \$HOME/.config/ml4w/scripts/ml4w-wallpaper to retint icons after theming"
REMOTE_WORKDIR='$HOME/.config/timhyperland-icons'
REMOTE_PATCH_PY="${REMOTE_WORKDIR}/hook_wallpaper_script.py"

run "mkdir -p ${REMOTE_WORKDIR} && cat > ${REMOTE_PATCH_PY}" <<'PATCHPY'
from pathlib import Path

path = Path.home() / ".config/ml4w/scripts/ml4w-wallpaper"
text = path.read_text()
# Not tied to this script's filename/number -- a rename/renumber here
# must not make an already-hooked target look un-hooked.
marker = "# >>> timhyperland-icons: retint adapted app/tray icons (see scripts/README.md)"

stale_line = "\n    $HOME/timhyperland/scripts/17-deploy-direct-path-icons.sh --local >&2"
if marker in text:
    if stale_line in text:
        # An older version of this hook also patched in a call to
        # 17-deploy-direct-path-icons.sh (direct-path/sudo icon
        # overrides), since removed -- strip just that stray line so an
        # already-hooked target self-heals on re-run instead of needing
        # manual cleanup.
        text = text.replace(stale_line, "")
        path.write_text(text)
        print("Removed stale call to the retired 17-deploy-direct-path-icons.sh.")
    else:
        print("Already hooked -- nothing to do.")
else:
    # generate_image_variants is the last step of ml4w-wallpaper's
    # "theming was NOT skipped" branch (run_matugen, reload_waybar,
    # reload_quickshell, reload_pywalfox, reload_swaync,
    # generate_image_variants) -- inserting right after its call keeps
    # our hook inside that same branch, so it's skipped along with the
    # rest of theming when the caller passes --skip-theming.
    call_line = "    generate_image_variants"
    idx = text.index(call_line)
    if idx != text.rindex(call_line):
        raise SystemExit(f"'{call_line}' is not unique in {path} -- refusing to guess which to patch")
    end = idx + len(call_line)
    hook = (
        "\n" + marker +
        "\n    $HOME/timhyperland/scripts/15-deploy-duotone-theme.sh --local >&2"
    )
    text = text[:end] + hook + text[end:]
    path.write_text(text)
    print("Hook installed.")
PATCHPY

run "python3 ${REMOTE_PATCH_PY}"

echo ">>> Done. Wallpaper changes made via ML4W's own picker/menu/keybindings will now"
echo "    re-tint icons too -- entirely from files already on the target, no network."
