#!/bin/bash

# omarchy:summary=Prompt for required reboot or service restarts after updates
# omarchy:args=[--services-only|--reboot-only]

kernel_modules_path="${OMARCHY_KERNEL_MODULES_PATH:-/usr/lib/modules}"

mode="${1:-all}"
case "$mode" in
  all|--services-only|--reboot-only) ;;
  *) echo "Unknown restart phase: $mode" >&2; exit 2 ;;
esac

echo
confirm_reboot() {
  if [[ ${OMARCHY_UPDATE_UNATTENDED:-0} == "1" ]]; then
    echo "$(omarchy-i18n update.rebootLater "$1" "omarchy-system reboot")"
  elif gum confirm --affirmative "$(omarchy-i18n common.yes)" --negative "$(omarchy-i18n common.no)" "$1"; then
    omarchy-system reboot
    exit 0
  fi
}

if [[ $mode != "--services-only" ]]; then
  running_kernel=$(uname -r)
  kernel_updated=true

  # Every kernel package owns modules.builtin; Arch Linux ARM's ships no vmlinuz here (#12440).
  if [[ -f $kernel_modules_path/$running_kernel/modules.builtin ]] &&
    dpkg -S "$kernel_modules_path/$running_kernel/modules.builtin" &>/dev/null; then
    kernel_updated=false
  fi

  if [[ $kernel_updated == "true" ]]; then
    confirm_reboot "$(omarchy-i18n update.kernelReboot)"
  elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then
    confirm_reboot "$(omarchy-i18n update.rebootRequired)"
  fi

  hyprland_updated=false
  while IFS= read -r hyprland_pid; do
    [[ -n $hyprland_pid ]] || continue
    if [[ $(readlink "/proc/$hyprland_pid/exe" 2>/dev/null) == *"(deleted)"* ]]; then
      hyprland_updated=true
      break
    fi
  done < <(pgrep -x Hyprland 2>/dev/null)
  if [[ $hyprland_updated == "true" ]]; then
    confirm_reboot "$(omarchy-i18n update.hyprlandReboot)"
  fi
fi

if [[ $mode != "--reboot-only" ]]; then
  for file in "$HOME"/.local/state/omarchy/restart-*-required; do
    if [[ -f $file ]]; then
      filename=$(basename "$file")
      service=$(echo "$filename" | sed 's/restart-\(.*\)-required/\1/')
      echo "$(omarchy-i18n update.restartingService "$service")"
      omarchy-state clear "$filename"
      omarchy-restart-"$service"
    fi
  done

  # Updates routinely replace the shell's QML, and a stale process can lazy-load
  # new files into old code. A restart failure (locked session, ssh, TTY) only
  # prints its reason: the next update or login gets a fresh shell anyway.
  echo -e "\e[32m\n$(omarchy-i18n update.restartingShell)\e[0m"
  echo "$(omarchy-i18n update.pluginsReloaded)"
  omarchy-restart-shell || true
fi
