#!/usr/bin/env bash
# Mirror the GNOME UI font into eww's font-family (analogous to accent.sh).
# The system font is set in the TANINUX/GTK appearance settings; eww follows it.
#   get      print the resolved family
#   apply    rewrite the font-family line in eww.scss + reload
#   watch    apply now, then re-apply whenever gsettings font-name changes
set -u
DIR="$(cd "$(dirname "$0")/.." && pwd)"
SCSS="$DIR/eww.scss"

family() {
  # Pango string e.g. "Iosevka Aile Semi-Bold 11" → family "Iosevka Aile".
  local f
  f=$(gsettings get org.gnome.desktop.interface font-name 2>/dev/null | sed "s/^'//; s/'$//")
  f=$(printf '%s' "$f" | sed -E 's/ [0-9]+(\.[0-9]+)?$//')   # drop size
  f=$(printf '%s' "$f" | sed -E 's/ (Thin|Extra-?Light|Light|Semi-?Light|Regular|Book|Medium|Semi-?Bold|Demi-?Bold|Bold|Extra-?Bold|Ultra-?Bold|Black|Heavy|Italic|Oblique|Condensed|Expanded)$//Ig')
  [ -n "$f" ] && printf '%s' "$f" || printf 'Iosevka Aile'
}

apply() {
  local fam; fam=$(family)
  sed -i -E "s|^(\s*font-family:).*|\1 \"$fam\", \"Symbols Nerd Font\", sans-serif;|" "$SCSS"
  eww reload >/dev/null 2>&1
}

case "${1:-apply}" in
  get)   family; echo ;;
  apply) apply ;;
  watch)
    apply
    last=$(gsettings get org.gnome.desktop.interface font-name 2>/dev/null)
    while :; do
      sleep 3
      now=$(gsettings get org.gnome.desktop.interface font-name 2>/dev/null)
      [ "$now" != "$last" ] && { last="$now"; apply; }
    done ;;
esac
