#!/bin/bash
# Reverts everything 10-generate-app-icons.sh / 11-deploy-icon-theme.sh
# installed on the target, back to the real original icons -- the opposite
# direction of 11.
#
# Two kinds of installed files, handled differently:
#   - Anywhere our override replaced a REAL pre-existing icon file (e.g.
#     kora's own art) -- 11 backed that up first, to
#     ~/.config/timhyperland-icons/original-icons-backup/<theme>/<relpath>.
#     Restored by copying it back over the live path.
#   - Everything under the generic hicolor/breeze-dark overlay (both the
#     standard scalable+raster mirrors 11 always writes per icon, and any
#     exact-path override that happens to land there too) -- there's
#     categorically no legitimate original to preserve at those paths, the
#     only real file for either theme is the root-owned system copy under
#     /usr/share/icons/ which this pipeline never touches, so even a
#     *backed-up* file there is only ever this pipeline's own earlier
#     output, never a true original. Those are deleted outright rather than
#     restored from backup -- see lib/icon_restore_plan.py for the full
#     reasoning.
#
# Which case applies to a given file is recomputed fresh each run from
# generated_icons/manifest.json -- no separate state to keep in sync, and
# safe to rerun any time.
#
# This does NOT touch generated_icons/ in this repo -- the cached
# silhouettes and manifest stay put, so re-theming afterward is just
# ./11-deploy-icon-theme.sh again, no need to re-trace anything.
#
# Restarts Quickshell at the end (same mechanism as 11) so the revert is
# visible immediately, not just on next login.
#
# Usage: 12-restore-original-icons.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"
MANIFEST="${GEN_DIR}/manifest.json"

if [ ! -f "$MANIFEST" ]; then
    echo "No ${MANIFEST} -- nothing was ever generated, nothing to restore." >&2
    exit 1
fi

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

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

echo ">>> [1/2] Computing the hicolor/breeze-dark override files to remove outright"
python3 ./lib/icon_restore_plan.py --manifest "$MANIFEST" > "${WORK}/delete_list.txt"
DELETE_COUNT=$(wc -l < "${WORK}/delete_list.txt")
echo "    ${DELETE_COUNT} file(s) to remove"

echo ">>> [2/2] Restoring on the target"
DELETE_LIST_REMOTE='$HOME/.config/timhyperland-icons/restore-delete-list.txt'
run "mkdir -p \$HOME/.config/timhyperland-icons && cat > ${DELETE_LIST_REMOTE}" < "${WORK}/delete_list.txt"

run_script <<'REMOTE'
set -euo pipefail
ICONS_DIR="$HOME/.local/share/icons"
BACKUP_DIR="$HOME/.config/timhyperland-icons/original-icons-backup"
DELETE_LIST="$HOME/.config/timhyperland-icons/restore-delete-list.txt"

restored=0
if [ -d "$BACKUP_DIR" ]; then
    while IFS= read -r -d '' f; do
        rel="${f#"$BACKUP_DIR"/}"
        # hicolor/breeze-dark backups are never a true original (see
        # icon_restore_plan.py) -- the delete-list below removes those instead.
        case "$rel" in
            hicolor/*|breeze-dark/*) continue ;;
        esac
        live="$ICONS_DIR/$rel"
        mkdir -p "$(dirname "$live")"
        cp "$f" "$live"
        restored=$((restored + 1))
    done < <(find "$BACKUP_DIR" -type f -print0)
fi

removed=0
if [ -s "$DELETE_LIST" ]; then
    while IFS= read -r rel; do
        [ -z "$rel" ] && continue
        f="$ICONS_DIR/$rel"
        if [ -f "$f" ]; then
            rm -f "$f"
            removed=$((removed + 1))
        fi
    done < "$DELETE_LIST"
fi

echo "Restored ${restored} file(s) from backup, removed ${removed} override-only file(s)"
rm -f "$DELETE_LIST"

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 restore is done and will" >&2
    echo "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."
