#!/bin/bash

# omarchy:summary=Start the default browser with no window, so it opens instantly later
# omarchy:hidden=true

# Run by omarchy-browser-prewarm.service. The launchers hand each new window to
# a running browser over its singleton socket in tens of milliseconds, where
# starting one takes hundreds.

default_browser=$(omarchy-cmd-default-browser)

# Read Exec= the way omarchy-launch-browser does, so this is the browser the
# launchers would start.
IFS=: read -ra data_dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
browser=""
for data_dir in "${data_dirs[@]}"; do
  entry="$data_dir/applications/$default_browser"
  [[ -f $entry ]] || continue
  while IFS= read -r line || [[ -n $line ]]; do
    line=${line%$'\r'}
    if [[ $line == Exec=* ]]; then
      browser=${line#Exec=}
      browser=${browser%% *}
      break
    fi
  done <"$entry"
  break
done

# Only a Chromium-based browser stays up this way, and only the browser itself:
# a wrapper in its place may pick a profile the launchers would never reach.
case $(type -P "$browser") in
/usr/bin/chromium | /usr/bin/google-chrome-stable | /usr/bin/brave | /usr/bin/brave-origin | /usr/bin/microsoft-edge-stable) ;;
*) exit 0 ;;
esac

# Without a window, Chromium exits once startup settles and again whenever its
# last window closes. --keep-alive-for-test holds it open through both.
exec "$browser" --no-startup-window --keep-alive-for-test
