#!/bin/bash

# omarchy:summary=Print the desktop entry ID of the default web browser
# omarchy:hidden=true

# Read the http handler from the config-dir mimeapps.list files the way xdg-mime
# does, desktop-specific list first, taking the first listed entry that is
# installed. xdg-settings reaches the same answer through several shell scripts
# in ~70ms, which every browser and web app launch would otherwise pay.
IFS=: read -ra data_dirs <<<"${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
IFS=: read -ra config_dirs <<<"${XDG_CONFIG_HOME:-$HOME/.config}:${XDG_CONFIG_DIRS:-/etc/xdg}"
IFS=: read -ra desktops <<<"${XDG_CURRENT_DESKTOP:-}"

# Installed means the command of the entry the launchers will read, the first
# one found, still resolves: an entry of Omarchy's own can outlive the browser
# it launched.
installed() {
  local data_dir command

  for data_dir in "${data_dirs[@]}"; do
    [[ -r $data_dir/applications/$1 ]] || continue
    command=$(sed -n 's/^Exec=\([^ ]*\).*/\1/p' "$data_dir/applications/$1" | head -1)
    [[ -n $command ]] && command -v "$command" >/dev/null
    return
  done

  return 1
}

for config_dir in "${config_dirs[@]}"; do
  for desktop in "${desktops[@]}" ""; do
    list="$config_dir/${desktop:+${desktop,,}-}mimeapps.list"
    [[ -f $list ]] || continue

    entries=$(awk '
      /^\[Default Applications\]/ { section = 1; next }
      /^\[/ { section = 0 }
      section && index($0, "x-scheme-handler/http=") == 1 { print substr($0, 23); exit }
    ' "$list")

    IFS=';' read -ra entries <<<"$entries"
    for entry in "${entries[@]}"; do
      if [[ -n $entry ]] && installed "$entry"; then
        echo "$entry"
        exit 0
      fi
    done
  done
done

# Nothing set in a config dir: let xdg-settings search the data dirs and caches.
# It consults $BROWSER too, which the session points back at omarchy-launch-browser.
browser=$(env -u BROWSER xdg-settings get default-web-browser 2>/dev/null)
if [[ -z $browser ]]; then
  browser=$(xdg-mime query default x-scheme-handler/https 2>/dev/null)
fi

[[ -n $browser ]] && echo "$browser"
