#!/bin/bash

# omarchy:summary=Launch a URL as a web app in the default supported browser
# omarchy:args=<url>

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

case $browser in
chromium* | google-chrome* | brave* | microsoft-edge* | opera* | vivaldi* | helium*) browsers=("$browser") ;;
# New installs have Chrome; older ones may only have the Chromium they shipped with.
*) browsers=(google-chrome.desktop chromium.desktop) ;;
esac

# Read Exec= from the same data dirs omarchy-cmd-default-browser searched, as
# omarchy-launch-browser does, so a browser it resolved is one this can start.
IFS=: read -ra data_dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
browser_exec=""
for browser in "${browsers[@]}"; do
  for data_dir in "${data_dirs[@]}"; do
    entry="$data_dir/applications/$browser"
    [[ -f $entry ]] || continue
    while IFS= read -r line || [[ -n $line ]]; do
      line=${line%$'\r'}
      if [[ $line == Exec=* ]]; then
        browser_exec=${line#Exec=}
        browser_exec=${browser_exec%% *}
        break
      fi
    done <"$entry"
    break 2
  done
done

# Handing an empty command to uwsm-app surfaces as "Command not found: \"\"",
# which fails a keybinding silently. A web app runs in a Chromium-based
# browser, so say that rather than claiming no browser is set.
if [[ -z $browser_exec ]]; then
  echo "omarchy-launch-webapp: web apps need a Chromium-based browser; install Chromium with 'omarchy install browser chromium'" >&2
  omarchy-notification-send -u critical -g 󰖟 "$(omarchy-i18n browser.webappNeedsChromium)" "$(omarchy-i18n browser.webappNeedsChromiumHint)"
  exit 1
fi

if ! omarchy-cmd-browser-handoff "$browser_exec" --app="$1" "${@:2}"; then
  exec setsid uwsm-app -- "$browser_exec" --app="$1" "${@:2}"
fi
