#!/usr/bin/env bash
set -euo pipefail

TARGET_DEFAULT="elphel@192.168.0.224"
TARGET="${TARGET:-$TARGET_DEFAULT}"
MODE="remote"
KWIN_ONLY=0
FORCE_DISPLAY="${DISPLAY_OVERRIDE:-}"
FORCE_XAUTH="${XAUTHORITY_OVERRIDE:-}"
SSH_CONNECT_TIMEOUT="${SSH_CONNECT_TIMEOUT:-7}"

usage() {
  cat <<'EOF'
Recover KDE desktop responsiveness without reboot.

Default mode:
  Connect to elphel@192.168.0.224 over SSH and run recovery there.

Usage:
  recover_kde_gui.sh [options]

Options:
  --target USER@HOST   SSH destination (default: elphel@192.168.0.224)
  --local              Run recovery on current machine (no SSH)
  --kwin-only          Restart only kwin service (skip plasmashell restart)
  --display VALUE      Force DISPLAY (example: :0)
  --xauthority PATH    Force XAUTHORITY path
  -h, --help           Show this help

Examples:
  recover_kde_gui.sh
  recover_kde_gui.sh --target elphel@192.168.0.224
  recover_kde_gui.sh --local --display :0
  recover_kde_gui.sh --local --kwin-only
EOF
}

log() {
  printf '[%s] %s\n' "$(date '+%F %T')" "$*"
}

detect_proc_env() {
  local pid="$1"
  local key="$2"
  if [[ -r "/proc/$pid/environ" ]]; then
    tr '\0' '\n' <"/proc/$pid/environ" | sed -n "s/^${key}=//p" | head -n1
  fi
}

recover_local() {
  local uid display xauth kwin_pid

  uid="$(id -u)"
  export XDG_RUNTIME_DIR="/run/user/$uid"

  if [[ ! -d "$XDG_RUNTIME_DIR" ]]; then
    log "ERROR: $XDG_RUNTIME_DIR is missing (no user runtime dir)."
    return 2
  fi

  log "Restarting plasma-kwin_x11.service"
  if ! systemctl --user restart plasma-kwin_x11.service; then
    log "ERROR: failed to restart plasma-kwin_x11.service"
    return 3
  fi

  if [[ "$KWIN_ONLY" -eq 1 ]]; then
    log "Done (kwin-only mode)."
    return 0
  fi

  kwin_pid="$(pgrep -u "$uid" -n -x kwin_x11 || true)"

  display="$FORCE_DISPLAY"
  if [[ -z "$display" && -n "$kwin_pid" ]]; then
    display="$(detect_proc_env "$kwin_pid" DISPLAY || true)"
  fi
  if [[ -z "$display" ]]; then
    display=":0"
  fi

  xauth="$FORCE_XAUTH"
  if [[ -z "$xauth" && -n "$kwin_pid" ]]; then
    xauth="$(detect_proc_env "$kwin_pid" XAUTHORITY || true)"
  fi
  if [[ -z "$xauth" ]]; then
    xauth="$HOME/.Xauthority"
  fi

  export DISPLAY="$display"
  export XAUTHORITY="$xauth"
  log "Using DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY"

  log "Restarting plasmashell"
  kquitapp5 plasmashell >/dev/null 2>&1 || true
  sleep 1
  kstart5 plasmashell >/dev/null 2>&1 || true

  if command -v qdbus >/dev/null 2>&1; then
    qdbus org.kde.KWin /Compositor suspend >/dev/null 2>&1 || true
    sleep 1
    qdbus org.kde.KWin /Compositor resume >/dev/null 2>&1 || true
  fi

  log "KDE recovery commands completed."
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --target)
      TARGET="$2"
      shift 2
      ;;
    --local)
      MODE="local"
      shift
      ;;
    --kwin-only)
      KWIN_ONLY=1
      shift
      ;;
    --display)
      FORCE_DISPLAY="$2"
      shift 2
      ;;
    --xauthority)
      FORCE_XAUTH="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if [[ "$MODE" == "remote" ]]; then
  log "Connecting to $TARGET"
  remote_cmd="$(printf "KWIN_ONLY=%q FORCE_DISPLAY=%q FORCE_XAUTH=%q bash -s -- --local" "$KWIN_ONLY" "$FORCE_DISPLAY" "$FORCE_XAUTH")"
  exec ssh -o BatchMode=yes -o ConnectTimeout="$SSH_CONNECT_TIMEOUT" "$TARGET" "$remote_cmd" <"$0"
fi

recover_local
