#!/usr/bin/env bash
# Emergency recovery when desktop shows wallpaper but no panels/UI after a profile change.
# Run from TTY: Ctrl+Alt+F3, log in, then:
#   sudo /path/to/z13Profiler/bin/z13-recover-desktop

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INSTALL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
export INSTALL_ROOT CONFIG_FILE="${INSTALL_ROOT}/config/profiles.conf"

# shellcheck source=../lib/memory-profiles.sh
source "${INSTALL_ROOT}/lib/memory-profiles.sh"

if [[ "${EUID}" -ne 0 ]]; then
    echo "Run with sudo." >&2
    exit 1
fi

echo "=== z13Profiler desktop recovery ==="
echo ""
echo "Memory now:"
free -h | sed 's/^/  /'
echo ""
if uma_base="$(find_uma_base 2>/dev/null)"; then
    echo "UMA carveout index: $(cat "${uma_base}/carveout")"
    sed 's/^/  /' "${uma_base}/carveout_options"
fi
echo ""

echo "Step 1: Reset memory profile to safe defaults (4 GB carveout, no custom TTM)..."
apply_profile reset

echo ""
echo "Step 2: Try restarting Plasma for logged-in user(s)..."
for udir in /run/user/*; do
    [[ -d "${udir}" ]] || continue
    uid="${udir##*/}"
    user="$(id -nu "${uid}" 2>/dev/null)" || continue
    [[ "${user}" == "root" ]] && continue
    echo "  Restarting plasmashell for ${user} (uid ${uid})..."
    sudo -u "${user}" DBUS_SESSION_BUS_ADDRESS="unix:path=${udir}/bus" \
        systemctl --user restart plasma-plasmashell 2>/dev/null \
        || sudo -u "${user}" kstart plasmashell 2>/dev/null \
        || true
done

echo ""
echo "If the panel still missing, reboot once more:"
echo "  sudo reboot"
echo ""
echo "After reboot, verify:"
echo "  z13-memory-profiles --status"
echo "  free -h"
