#!/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=""
browser_class=""
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 [[ -z $browser_exec && $line == Exec=* ]]; then
      browser_exec=${line#Exec=}
      browser_exec=${browser_exec%% *}
    elif [[ -z $browser_class && $line == StartupWMClass=* ]]; then
      browser_class=${line#StartupWMClass=}
    fi
    [[ -n $browser_exec && -n $browser_class ]] && break
  done <"$entry"
  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.
has_private=false
for argument in "$@"; do
  if [[ $argument == "--private" ]]; then
    has_private=true
    break
  fi
done

private_flag="--private"
if [[ $has_private == "true" ]]; then
  if [[ $browser_exec =~ [Ll]adybird ]]; then
    # Ladybird has no private window and refuses to start on a flag it doesn't
    # know. A profile that is deleted when it closes is its nearest equivalent.
    private_flag="--temporary-profile"
  elif $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

launch_args=()
for argument in "$@"; do
  if [[ $argument == "--private" ]]; then
    launch_args+=("$private_flag")
  else
    launch_args+=("$argument")
  fi
done

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

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

if [[ -n $url && -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]]; then
  # The binary name is only a guess at the window class (Zen runs zen-bin as
  # class zen), so prefer the class the desktop entry declares, then the guess.
  guessed_pattern="^$(basename "$browser_exec" -stable).*$"
  if [[ -n $browser_class ]]; then
    omarchy-hyprland-focus-app "^$browser_class$" ||
      omarchy-hyprland-focus-app "$guessed_pattern" || true
  else
    omarchy-hyprland-focus-app "$guessed_pattern" || true
  fi
fi
