#!/bin/bash

# omarchy:summary=Restart the browser kept running hidden, unless its windows are open
# omarchy:args=[--quiet|--force]

# The hidden browser keeps running the binary it started from, so an update
# restarts it too. Restarting under open windows would lose their tabs, so it
# waits for them to close, unless forced, and only a restart someone asked for
# says so.
if omarchy-runs-browser; then
  case ${1:-} in
  --force) reopen=1 ;;
  --quiet) exit 0 ;;
  *)
    omarchy-notification-send -g 󰖟 "$(omarchy-i18n browser.restartCloseWindows)"
    exit 0
    ;;
  esac
fi

# A browser running without the prewarm would keep the next window to itself,
# so every one is closed, with SIGTERM, its own clean shutdown.
browsers='chrome|chromium|brave|msedge|firefox'
if pkill -u "$USER" -x "$browsers"; then
  for _ in {1..50}; do
    pgrep -u "$USER" -x "$browsers" >/dev/null || break
    sleep 0.2
  done
  pgrep -u "$USER" -x "$browsers" >/dev/null && exit 1
fi

systemctl --user restart omarchy-browser-prewarm.service 2>/dev/null || true

if [[ -n ${reopen:-} ]]; then
  setsid omarchy-launch-browser >/dev/null 2>&1 &
fi
