#!/bin/bash

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

# Read the http handler from mimeapps.list files in XDG MIME Apps spec order
# (config dirs, then data dirs' applications/, desktop-specific list first),
# taking the first listed entry that is installed. xdg-settings reaches the
# same answer through several shell scripts in ~35-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 line command

  for data_dir in "${data_dirs[@]}"; do
    [[ -r $data_dir/applications/$1 ]] || continue
    command=""
    while IFS= read -r line || [[ -n $line ]]; do
      line=${line%$'\r'}
      if [[ $line == Exec=* ]]; then
        command=${line#Exec=}
        command=${command%% *}
        break
      fi
    done <"$data_dir/applications/$1"
    [[ -n $command ]] && command -v "$command" >/dev/null
    return
  done

  return 1
}

read_default_http() {
  local file="$1" line section=0
  REPLY=""

  while IFS= read -r line || [[ -n $line ]]; do
    line=${line%$'\r'}
    if [[ $line =~ ^\[Default\ Applications\][[:blank:]]*$ ]]; then
      section=1
    elif [[ $line == "["* ]]; then
      section=0
    elif (( section )) && [[ $line == x-scheme-handler/http=* ]]; then
      REPLY=${line#x-scheme-handler/http=}
      return 0
    fi
  done <"$file"

  return 1
}

mimeapps_dirs=("${config_dirs[@]}")
for data_dir in "${data_dirs[@]}"; do
  mimeapps_dirs+=("$data_dir/applications")
done

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

    read_default_http "$list" || continue

    # omarchy-browser.desktop only routes links back through
    # omarchy-launch-browser, so the browser is whatever is listed after it.
    IFS=';' read -ra entries <<<"$REPLY"
    for entry in "${entries[@]}"; do
      if [[ -n $entry && $entry != "omarchy-browser.desktop" ]] && 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,
# and the desktop-specific list, which points at omarchy-browser.desktop.
#
# Either answer can outlive its browser, so an entry is only taken once
# installed() agrees, and xdg-mime still gets its say when xdg-settings names
# one that is gone.
browser=$(env -u BROWSER XDG_CURRENT_DESKTOP= xdg-settings get default-web-browser 2>/dev/null)
if [[ -n $browser && $browser != "omarchy-browser.desktop" ]] && installed "$browser"; then
  echo "$browser"
  exit 0
fi

browser=$(XDG_CURRENT_DESKTOP= xdg-mime query default x-scheme-handler/https 2>/dev/null)
if [[ -n $browser && $browser != "omarchy-browser.desktop" ]] && installed "$browser"; then
  echo "$browser"
  exit 0
fi

# With the listed handler gone, both tools settle on the routing entry, which
# only hands links back to omarchy-launch-browser. Take the first installed
# https handler the data dirs still list, so a stale list cannot leave every
# launch empty.
for data_dir in "${data_dirs[@]}"; do
  cache="$data_dir/applications/mimeinfo.cache"
  [[ -r $cache ]] || continue

  while IFS= read -r line || [[ -n $line ]]; do
    line=${line%$'\r'}
    [[ $line == x-scheme-handler/https=* ]] || continue
    IFS=';' read -ra entries <<<"${line#x-scheme-handler/https=}"
    for entry in "${entries[@]}"; do
      if [[ -n $entry && $entry != "omarchy-browser.desktop" ]] && installed "$entry"; then
        echo "$entry"
        exit 0
      fi
    done
  done <"$cache"
done

exit 1
