#!/bin/bash

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

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

# Read Exec= from the same data dirs omarchy-cmd-default-browser searched, in
# the same order, so the command always comes from the entry that was checked.
IFS=: read -ra data_dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
browser_exec=""
for data_dir in "${data_dirs[@]}"; do
  entry="$data_dir/applications/$default_browser"
  [[ -f $entry ]] || continue
  browser_exec=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' "$entry" | head -1)
  break
done

# Handing an empty command to uwsm-app surfaces as "Command not found: \"\"",
# which fails a keybinding silently. Say what is missing and how to fix it.
if [[ -z $browser_exec ]]; then
  echo "omarchy-launch-browser: no default browser found; set one with 'omarchy default browser <browser>'" >&2
  omarchy-notification-send -u critical -g 󰖟 "$(omarchy-i18n browser.notFound)" "$(omarchy-i18n browser.notFoundHint)"
  exit 1
fi

# Only a private launch needs the browser's flag, and probing a Firefox-family
# browser's --help starts the whole binary, so ordinary launches skip it and
# leave their arguments as they are.
private_flag="--private"
if [[ " $* " == *" --private "* ]]; then
  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
fi

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

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
