#!/bin/bash

# omarchy:summary=Launch the default browser as determined by xdg-settings.
# omarchy:args=[url]

default_browser=$(env -u BROWSER xdg-settings get default-web-browser)
if [[ -z $default_browser ]]; then
  default_browser=$(xdg-mime query default x-scheme-handler/https)
fi
browser_exec=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' {~/.local,~/.nix-profile,/usr}/share/applications/$default_browser 2>/dev/null | head -1)

if $browser_exec --help 2>/dev/null | grep -q MOZ_LOG; then
  private_flag="--private-window"
elif [[ $browser_exec =~ edge ]]; then
  private_flag="--inprivate"
else
  private_flag="--incognito"
fi

systemd-run --user --quiet --collect --unit="omarchy-browser-$(date +%s%N)" \
  --property=StandardOutput=null --property=StandardError=null \
  uwsm-app -- "$browser_exec" "${@/--private/$private_flag}"

url=""
for argument in "$@"; do
  if [[ $argument != "--private" ]]; then
    url=$argument
    break
  fi
done

if [[ -n $url && -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
  omarchy-hyprland-focus-app "^$(basename "$browser_exec" -stable).*$" || true
fi
