#!/bin/bash

# omarchy:summary=Prompt for required reboot or service restarts after updates

echo

running_kernel=$(uname -r)
kernel_updated=false

for kernel in /usr/lib/modules/*/vmlinuz; do
  if [[ -f $kernel ]] && pacman -Qo "$kernel" &>/dev/null; then
    installed_kernel=$(basename "$(dirname "$kernel")")

    if [[ $installed_kernel != $running_kernel ]]; then
      kernel_updated=true
      break
    fi
  fi
done

if [[ $kernel_updated == "true" ]]; then
  gum confirm "Linux kernel has been updated. Reboot?" && omarchy-system-reboot
elif [[ -f $HOME/.local/state/omarchy/reboot-required ]]; then
  gum confirm "Updates require reboot. Ready?" && omarchy-system-reboot
fi

running_hyprland=$(readlink /proc/$(pgrep -x Hyprland)/exe 2>/dev/null)
if [[ $running_hyprland == *"(deleted)"* ]]; then
  gum confirm "Hyprland has been updated. Reboot?" && omarchy-system-reboot
fi

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 "Restarting $service"
    omarchy-state clear "$filename"
    omarchy-restart-"$service"
  fi
done
