#!/bin/sh
# Live-replace a running X11 session / window manager with ANODE (strict POSIX sh)
set -eu

: "${XDG_CONFIG_HOME:=$HOME/.config}"
: "${XDG_CACHE_HOME:=$HOME/.cache}"
: "${ANODE_PREFIX:=/usr/local}"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"

PROFILE="${ANODE_SESSION_PROFILE:-}"
KEEP_PANELS=0
FOREGROUND=0
NO_AUTOSTART=0
FORCE=0
SWITCH_SESSION=0
DRY_RUN=0

usage() {
  cat <<'EOF'
Usage: anode-replace [OPTIONS]

Live-replace the currently running X11 window manager / session with ANODE, or
switch to a fresh ANODE display-manager session.

Options:
  --profile NAME    Pass session autostart profile NAME to anode-session
  --keep-panels     Do not stop existing panel, notification, or xsettings daemons
  --foreground      Exec anode-session in the foreground instead of detaching
  --no-autostart    Skip anode-autostart start during replacement
  --force           Proceed with in-place replacement even if WM is DM session leader
  --switch-session  Switch to an ANODE LightDM session cleanly (schedules one-shot ~/.xprofile handoff when a user session is already active)
  --dry-run         Print detected WM and planned actions without replacing
  -h, --help        Show this help
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --profile)
      [ $# -ge 2 ] || { printf 'anode-replace: --profile requires a name\n' >&2; exit 2; }
      PROFILE="$2"
      shift 2
      ;;
    --profile=*)
      PROFILE="${1#--profile=}"
      shift
      ;;
    --keep-panels)
      KEEP_PANELS=1
      shift
      ;;
    --foreground)
      FOREGROUND=1
      shift
      ;;
    --no-autostart)
      NO_AUTOSTART=1
      shift
      ;;
    --force)
      FORCE=1
      shift
      ;;
    --switch-session)
      SWITCH_SESSION=1
      shift
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf 'anode-replace: unknown argument: %s\n' "$1" >&2
      exit 2
      ;;
  esac
done

case ":$PATH:" in
  *":$SCRIPT_DIR:"*) ;;
  *) PATH="$SCRIPT_DIR:$PATH" ;;
esac
case ":$PATH:" in
  *":$ANODE_PREFIX/bin:"*) ;;
  *) PATH="$ANODE_PREFIX/bin:$PATH" ;;
esac
export PATH

ANODE_SESSION_BIN="$(command -v anode-session 2>/dev/null || true)"
if [ -z "$ANODE_SESSION_BIN" ]; then
  printf 'anode-replace: error: anode-session not found on PATH\n' >&2
  exit 1
fi

get_root_wm_win() {
  [ -n "${DISPLAY:-}" ] || return 0
  command -v xprop >/dev/null 2>&1 || return 0
  xprop -root _NET_SUPPORTING_WM_CHECK 2>/dev/null | awk '
    /window id/ {
      for (i = 1; i <= NF; i++) {
        if ($i ~ /^0x[0-9a-fA-F]+/) {
          sub(/,$/, "", $i)
          print $i
          exit
        }
      }
    }
  '
}

get_win_wm_name() {
  _wid="$1"
  [ -n "$_wid" ] && [ -n "${DISPLAY:-}" ] || return 0
  command -v xprop >/dev/null 2>&1 || return 0
  _nm="$(xprop -id "$_wid" _NET_WM_NAME 2>/dev/null | awk '
    index($0, "=") > 0 {
      v = $0
      sub(/^[^=]*=[ \t]*"?/, "", v)
      sub(/"?[ \t]*$/, "", v)
      print v
      exit
    }
  ')"
  if [ -n "$_nm" ]; then
    printf '%s\n' "$_nm"
    return 0
  fi
  xprop -id "$_wid" WM_NAME 2>/dev/null | awk '
    index($0, "=") > 0 {
      v = $0
      sub(/^[^=]*=[ \t]*"?/, "", v)
      sub(/"?[ \t]*$/, "", v)
      print v
      exit
    }
  '
}

get_win_pid() {
  _wid="$1"
  [ -n "$_wid" ] && [ -n "${DISPLAY:-}" ] || return 0
  command -v xprop >/dev/null 2>&1 || return 0
  xprop -id "$_wid" _NET_WM_PID 2>/dev/null | awk '
    index($0, "=") > 0 {
      v = $0
      sub(/^[^=]*=[ \t]*/, "", v)
      gsub(/[^0-9]/, "", v)
      if (v != "") {
        print v
        exit
      }
    }
  '
}

MY_UID="$(id -u)"
SELF_PID="$$"

norm_display() {
  case "${1:-}" in
    *.0) printf '%s\n' "${1%.0}" ;;
    *)   printf '%s\n' "${1:-}" ;;
  esac
}

pid_matches_display() {
  _p="$1"
  [ -n "${DISPLAY:-}" ] || return 0
  if [ -d "/proc/$SELF_PID" ]; then
    [ -r "/proc/$_p/environ" ] || return 1
    _pdisp="$(tr '\0' '\n' < "/proc/$_p/environ" 2>/dev/null | awk 'substr($0, 1, 8) == "DISPLAY=" { print substr($0, 9); exit }' || true)"
    [ -n "${_pdisp:-}" ] || return 1
    [ "$(norm_display "$_pdisp")" = "$(norm_display "$DISPLAY")" ] && return 0
    return 1
  fi
  _pe="$(ps eww -p "$_p" 2>/dev/null || true)"
  if [ -n "${_pe:-}" ]; then
    _pdisp="$(printf '%s\n' "$_pe" | awk '
      {
        for (i = 1; i <= NF; i++) {
          if (substr($i, 1, 8) == "DISPLAY=") {
            print substr($i, 9)
            exit
          }
        }
      }
    ' || true)"
    if [ -n "${_pdisp:-}" ]; then
      [ "$(norm_display "$_pdisp")" = "$(norm_display "$DISPLAY")" ] && return 0
      return 1
    fi
  fi
  return 0
}

find_wm_pid_by_name() {
  _wmname="$1"
  [ -n "$_wmname" ] || return 0
  _tok="$(printf '%s' "$_wmname" | awk '{
    w = tolower($1)
    gsub(/[^a-z0-9._-]/, "", w)
    if (w == "anode") w = "dwm"
    print w
    exit
  }')"
  [ -n "$_tok" ] || return 0
  (ps -eo uid=,pid=,comm= 2>/dev/null || ps -ax -o uid=,pid=,comm= 2>/dev/null || true) | awk -v u="$MY_UID" -v s="$SELF_PID" -v t="$_tok" '
    $1 == u && $2 > 1 && $2 != s {
      c = $3
      sub(/^.*\//, "", c)
      if (tolower(c) == t) {
        print $2
      }
    }
  ' | while read -r _wpid; do
    if pid_matches_display "$_wpid"; then
      printf '%s\n' "$_wpid"
      break
    fi
  done
}

get_ppid() {
  _p="$1"
  [ -n "$_p" ] || return 0
  (ps -eo pid=,ppid= 2>/dev/null || ps -ax -o pid=,ppid= 2>/dev/null || true) | awk -v t="$_p" '
    $1 == t { print $2; exit }
  '
}

get_pid_comm() {
  _p="$1"
  [ -n "$_p" ] || return 0
  (ps -eo pid=,comm= 2>/dev/null || ps -ax -o pid=,comm= 2>/dev/null || true) | awk -v t="$_p" '
    $1 == t {
      c = $2
      sub(/^.*\//, "", c)
      print c
      exit
    }
  '
}

is_session_leader_parent() {
  case "${1:-}" in
    lightdm|sddm|sddm-helper|gdm|gdm-x-session|gdm-session-wor*|xdm|lxdm|lxdm-binary|slim|ly|greetd|emptty|xinit|startx|Xsession|xsession|login|agetty)
      return 0
      ;;
  esac
  return 1
}

is_my_pid() {
  _p="$1"
  [ -n "$_p" ] || return 1
  (ps -eo uid=,pid= 2>/dev/null || ps -ax -o uid=,pid= 2>/dev/null || true) | awk -v u="$MY_UID" -v t="$_p" '
    $1 == u && $2 == t { found = 1; exit 0 }
    END { exit found ? 0 : 1 }
  '
}

kill_my_procs() {
  (ps -eo uid=,pid=,comm= 2>/dev/null || ps -ax -o uid=,pid=,comm= 2>/dev/null || true) | awk -v u="$MY_UID" -v s="$SELF_PID" -v list="$*" '
    BEGIN {
      n = split(list, arr, /[ \t]+/)
      for (i = 1; i <= n; i++) {
        if (arr[i] != "") want[arr[i]] = 1
      }
    }
    $1 == u && $2 > 1 && $2 != s {
      c = $3
      sub(/^.*\//, "", c)
      if (c in want) print $2
    }
  ' | while read -r _kpid; do
    if pid_matches_display "$_kpid"; then
      kill -TERM "$_kpid" 2>/dev/null || true
    fi
  done
}

dm_user_has_active_session() {
  _u="$1"
  command -v dm-tool >/dev/null 2>&1 || return 1
  dm-tool list-seats 2>/dev/null | awk -v u="$_u" -v sq="'" '
    {
      s = $0
      gsub(/^[ \t]+|[ \t]+$/, "", s)
      if (s == ("UserName=" sq u sq) || s == ("UserName=\"" u "\"") || s == ("UserName=" u)) {
        found = 1
        exit 0
      }
    }
    END { exit found ? 0 : 1 }
  '
}

ensure_xprofile_hook() {
  _xp="$HOME/.xprofile"
  if [ -f "$_xp" ] && grep -q '^# >>> anode-switch-once >>>$' "$_xp" 2>/dev/null; then
    return 0
  fi
  if [ -s "$_xp" ]; then
    printf '\n' >> "$_xp"
  fi
  cat <<'EOF' >> "$_xp"
# >>> anode-switch-once >>>
_anode_sw="${XDG_CACHE_HOME:-$HOME/.cache}/anode/switch-once"
if [ -r "$_anode_sw" ]; then
  _anode_bin=""
  _anode_prof=""
  { IFS= read -r _anode_bin || true; IFS= read -r _anode_prof || true; } < "$_anode_sw"
  rm -f "$_anode_sw"
  if [ -n "$_anode_bin" ] && [ -x "$_anode_bin" ]; then
    case "${0:-}" in
      *Xsession*)
        if [ -n "$_anode_prof" ]; then
          set -- "$_anode_bin" --profile "$_anode_prof"
        else
          set -- "$_anode_bin"
        fi
        ;;
      *)
        if [ -n "$_anode_prof" ]; then
          exec "$_anode_bin" --profile "$_anode_prof"
        else
          exec "$_anode_bin"
        fi
        ;;
    esac
  fi
fi
unset _anode_sw _anode_bin _anode_prof
# <<< anode-switch-once <<<
EOF
}

sync_activation_env() {
  [ "${ANODE_NO_DBUS:-0}" = "1" ] && return 0
  if command -v dbus-update-activation-environment >/dev/null 2>&1; then
    dbus-update-activation-environment --systemd \
      XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \
      DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || \
    dbus-update-activation-environment \
      XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \
      DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true
  fi
  if command -v systemctl >/dev/null 2>&1; then
    systemctl --user set-environment \
      XDG_CURRENT_DESKTOP=ANODE XDG_SESSION_DESKTOP=anode \
      DESKTOP_SESSION=anode XDG_SESSION_TYPE=x11 >/dev/null 2>&1 || true
    systemctl --user unset-environment \
      KDE_FULL_SESSION KDE_SESSION_VERSION KDE_SESSION_UID \
      GNOME_DESKTOP_SESSION_ID MATE_DESKTOP_SESSION_ID CINNAMON_VERSION \
      XFCE_SESSION LXQT_SESSION_CONFIG TDE_FULL_SESSION \
      HYPRLAND_INSTANCE_SIGNATURE SWAYSOCK I3SOCK BSPWM_SOCKET \
      WINDOWMAKER E_START GDMSESSION \
      GDK_SCALE GDK_DPI_SCALE >/dev/null 2>&1 || true
    if [ "${ANODE_KEEP_GTK_THEME:-0}" != "1" ]; then
      systemctl --user unset-environment GTK_THEME >/dev/null 2>&1 || true
    fi
  fi
}

PREV_WM_WIN="$(get_root_wm_win || true)"
PREV_WM_NAME="$(get_win_wm_name "${PREV_WM_WIN:-}" || true)"
PREV_WM_PID="$(get_win_pid "${PREV_WM_WIN:-}" || true)"
if [ -z "${PREV_WM_PID:-}" ] && [ -n "${PREV_WM_NAME:-}" ]; then
  PREV_WM_PID="$(find_wm_pid_by_name "$PREV_WM_NAME" || true)"
fi

PREV_WM_PPID=""
PREV_WM_PCOMM=""
IS_DM_SESSION_LEADER=0
if [ -n "${PREV_WM_PID:-}" ]; then
  PREV_WM_PPID="$(get_ppid "$PREV_WM_PID" || true)"
  if [ -n "${PREV_WM_PPID:-}" ]; then
    PREV_WM_PCOMM="$(get_pid_comm "$PREV_WM_PPID" || true)"
    if is_session_leader_parent "${PREV_WM_PCOMM:-}"; then
      IS_DM_SESSION_LEADER=1
    fi
  fi
fi

if [ "$SWITCH_SESSION" = "1" ]; then
  TARGET_USER="${USER:-$(id -un)}"
  if command -v dm-tool >/dev/null 2>&1 && ! dm_user_has_active_session "$TARGET_USER"; then
    if [ "$DRY_RUN" = "1" ]; then
      printf 'Would run: dm-tool switch-to-user %s anode\n' "$TARGET_USER"
      exit 0
    fi
    if [ ! -r /usr/share/xsessions/anode.desktop ] && [ ! -r /usr/share/lightdm/sessions/anode.desktop ]; then
      printf 'anode-replace: error: anode.desktop is not installed in /usr/share/xsessions or /usr/share/lightdm/sessions\n' >&2
      printf 'Run: sudo make XSESSIONSDIR=/usr/share/xsessions install\n' >&2
      exit 1
    fi
    exec dm-tool switch-to-user "$TARGET_USER" anode
  fi

  SWITCH_FILE="$XDG_CACHE_HOME/anode/switch-once"
  _wm_low="$(printf '%s' "${PREV_WM_NAME:-}" | awk '{ print tolower($1) }')"
  _exit_desc="log out manually"
  if [ "$_wm_low" = "i3" ] && [ -n "${DISPLAY:-}" ] && command -v i3-msg >/dev/null 2>&1; then
    _exit_desc="i3-msg exit"
  elif [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then
    _exit_desc="kill -TERM $PREV_WM_PID"
  fi

  if [ "$DRY_RUN" = "1" ]; then
    printf 'Display: %s\n' "${DISPLAY:-unset}"
    printf 'Detected WM: %s (window=%s pid=%s parent=%s)\n' \
      "${PREV_WM_NAME:-none}" "${PREV_WM_WIN:-none}" "${PREV_WM_PID:-unknown}" "${PREV_WM_PCOMM:-unknown}"
    if dm_user_has_active_session "$TARGET_USER"; then
      printf 'Note: LightDM already has an active session for %s (dm-tool switch-to-user refocuses it without starting ANODE).\n' "$TARGET_USER"
    fi
    printf 'Switch sentinel: %s\n' "$SWITCH_FILE"
    printf 'Profile hook: %s/.xprofile\n' "$HOME"
    printf 'Target session: %s%s\n' "$ANODE_SESSION_BIN" "$( [ -n "$PROFILE" ] && printf ' --profile %s' "$PROFILE" || true )"
    printf 'WM exit action: %s\n' "$_exit_desc"
    exit 0
  fi

  mkdir -p "$XDG_CACHE_HOME/anode"
  printf '%s\n%s\n' "$ANODE_SESSION_BIN" "$PROFILE" > "$SWITCH_FILE"
  ensure_xprofile_hook
  printf 'Scheduled one-shot ANODE session via ~/.xprofile; exiting %s to switch...\n' "${PREV_WM_NAME:-current WM}"

  if [ "$_wm_low" = "i3" ] && [ -n "${DISPLAY:-}" ] && command -v i3-msg >/dev/null 2>&1; then
    unset I3SOCK SWAYSOCK || true
    if i3-msg exit >/dev/null 2>&1; then
      exit 0
    fi
  fi
  if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then
    kill -TERM "$PREV_WM_PID" 2>/dev/null || true
    exit 0
  fi
  printf 'Log out of your current session and LightDM will start ANODE.\n'
  exit 0
fi

if [ -z "${DISPLAY:-}" ]; then
  printf 'anode-replace: error: DISPLAY is not set (run inside an active X11 session)\n' >&2
  exit 1
fi

unset KDE_FULL_SESSION KDE_SESSION_VERSION KDE_SESSION_UID \
      GNOME_DESKTOP_SESSION_ID MATE_DESKTOP_SESSION_ID CINNAMON_VERSION \
      XFCE_SESSION LXQT_SESSION_CONFIG TDE_FULL_SESSION \
      HYPRLAND_INSTANCE_SIGNATURE SWAYSOCK I3SOCK BSPWM_SOCKET \
      WINDOWMAKER E_START GDMSESSION \
      GDK_SCALE GDK_DPI_SCALE || true
if [ "${ANODE_KEEP_GTK_THEME:-0}" != "1" ]; then
  unset GTK_THEME || true
fi

XDG_CURRENT_DESKTOP="ANODE"
XDG_SESSION_DESKTOP="anode"
DESKTOP_SESSION="anode"
XDG_SESSION_TYPE="x11"
export XDG_CURRENT_DESKTOP XDG_SESSION_DESKTOP DESKTOP_SESSION XDG_SESSION_TYPE
if [ -n "$PROFILE" ]; then
  ANODE_SESSION_PROFILE="$PROFILE"
  export ANODE_SESSION_PROFILE
fi

set -- --replace
if [ -n "$PROFILE" ]; then
  set -- "$@" --profile "$PROFILE"
fi
if [ "$NO_AUTOSTART" = "1" ]; then
  set -- "$@" --no-autostart
fi

if [ "$DRY_RUN" = "1" ]; then
  printf 'Display: %s\n' "$DISPLAY"
  printf 'Detected WM: %s (window=%s pid=%s)\n' \
    "${PREV_WM_NAME:-none}" "${PREV_WM_WIN:-none}" "${PREV_WM_PID:-unknown}"
  printf 'Parent process: %s (pid=%s)\n' \
    "${PREV_WM_PCOMM:-unknown}" "${PREV_WM_PPID:-unknown}"
  if [ "$IS_DM_SESSION_LEADER" = "1" ]; then
    printf 'Warning: %s is the direct session child of %s; in-place replacement will end that session unless using --switch-session or ANODE at login.\n' \
      "${PREV_WM_NAME:-WM}" "$PREV_WM_PCOMM"
  fi
  printf 'Panel cleanup: %s\n' "$( [ "$KEEP_PANELS" = "1" ] && printf 'skipped (--keep-panels)' || printf 'enabled' )"
  printf 'Target identity: DE=ANODE, WM=ANODE WM\n'
  printf 'Command: %s' "$ANODE_SESSION_BIN"
  for _arg in "$@"; do
    printf ' %s' "$_arg"
  done
  printf '\n'
  exit 0
fi

if [ "$IS_DM_SESSION_LEADER" = "1" ] && [ "$FORCE" != "1" ]; then
  {
    printf 'anode-replace: error: %s (pid %s) is running directly as the session child of %s (pid %s).\n' \
      "${PREV_WM_NAME:-the active WM}" "${PREV_WM_PID:-unknown}" \
      "${PREV_WM_PCOMM:-the display manager}" "${PREV_WM_PPID:-unknown}"
    printf 'Replacing it in place causes %s to end the X11 session and kill the display.\n' \
      "${PREV_WM_PCOMM:-the display manager}"
    printf 'Use one of these safe alternatives instead:\n'
    printf '  1. Install anode.desktop into /usr/share/xsessions and switch via ~/.xprofile/display manager:\n'
    printf '       sudo make XSESSIONSDIR=/usr/share/xsessions install\n'
    printf '       anode-replace --switch-session\n'
    printf '     (Or select ANODE at login / set user-session=anode in /etc/lightdm/lightdm.conf.)\n'
    printf '  2. Pass --force only if you intentionally want to trigger WM replacement anyway.\n'
  } >&2
  exit 1
fi

sync_activation_env

# Stop duplicate ANODE session daemons from an earlier ANODE instance
kill_my_procs anode-statusd anode-powerd anode-touchd anode-vkbd

# Optionally stop conflicting third-party panels, notification daemons, and settings daemons
if [ "$KEEP_PANELS" != "1" ]; then
  kill_my_procs \
    xfce4-panel mate-panel lxpanel i3bar tint2 polybar lemonbar fbpanel plank wingpanel \
    dunst xfce4-notifyd xsettingsd xfsettingsd
fi

if [ "$FOREGROUND" = "1" ]; then
  if [ -n "${PREV_WM_PID:-}" ] && is_my_pid "$PREV_WM_PID"; then
    (
      sleep 1.5
      _cur_win="$(get_root_wm_win || true)"
      if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && kill -0 "$PREV_WM_PID" 2>/dev/null; then
        kill -TERM "$PREV_WM_PID" 2>/dev/null || true
      fi
    ) </dev/null >/dev/null 2>&1 &
  fi
  exec "$ANODE_SESSION_BIN" "$@"
fi

(
  trap '' HUP
  exec "$ANODE_SESSION_BIN" "$@"
) </dev/null >/dev/null 2>&1 &
SESSION_PID=$!

_tick=0
_fallback_sent=0
_replaced=0
while [ "$_tick" -lt 50 ]; do
  if ! kill -0 "$SESSION_PID" 2>/dev/null; then
    printf 'anode-replace: error: anode-session exited prematurely\n' >&2
    exit 1
  fi

  if [ "$_tick" -ge 15 ] && [ "$_fallback_sent" = "0" ] && [ -n "${PREV_WM_PID:-}" ]; then
    _cur_win="$(get_root_wm_win || true)"
    if [ -n "${PREV_WM_WIN:-}" ] && [ "$_cur_win" = "$PREV_WM_WIN" ] && is_my_pid "$PREV_WM_PID"; then
      kill -TERM "$PREV_WM_PID" 2>/dev/null || true
      _fallback_sent=1
    fi
  fi

  if command -v xprop >/dev/null 2>&1; then
    _cur_win="$(get_root_wm_win || true)"
    if [ -n "${_cur_win:-}" ] && [ "$_cur_win" != "${PREV_WM_WIN:-}" ]; then
      _cur_name="$(get_win_wm_name "$_cur_win" || true)"
      case "$_cur_name" in
        *ANODE*)
          _replaced=1
          break
          ;;
      esac
    fi
  elif [ "$_tick" -ge 5 ]; then
    _replaced=1
    break
  fi

  _tick=$(( _tick + 1 ))
  sleep 0.1
done

if [ "$_replaced" != "1" ]; then
  printf 'anode-replace: error: timed out waiting for ANODE WM to take over %s\n' "$DISPLAY" >&2
  exit 1
fi

printf 'ANODE is now running on %s (DE: ANODE, WM: ANODE WM)\n' "$DISPLAY"
