#!/bin/bash

# omarchy:summary=Apply current Omarchy theme colors and background alpha to running Foot terminals
# omarchy:hidden=true

colors_toml=$HOME/.local/state/omarchy/current/theme/colors.toml
foot_ini=$HOME/.local/state/omarchy/current/theme/foot.ini

[[ -f $colors_toml ]] || exit 0

# Theme switches wait on this retint, and pgrep scans every process, so it runs
# once; each terminal's shells come from the kernel's list of its children.
foot_pids=$(pgrep -x foot) || exit 0

foot_osc=$(omarchy-theme-osc "$colors_toml")
[[ -n $foot_osc ]] || exit 0

# foot takes a background alpha as an urxvt-style [percent] prefix, so a theme
# going see-through or back, as with Glassy windows, reaches running terminals.
# The last alpha in the theme's foot.ini wins, as it does when foot reads it.
alpha=$(sed -n 's/^[[:space:]]*alpha[[:space:]]*=[[:space:]]*\([0-9.]*\).*/\1/p' "$foot_ini" 2>/dev/null | tail -n 1)
background=$(omarchy-theme-color --file "$colors_toml" background 2>/dev/null)
if [[ -n $background ]]; then
  percent=$(awk -v alpha="${alpha:-1}" 'BEGIN { printf "%d", alpha * 100 + 0.5 }')
  foot_osc+=$(printf '\033]11;[%d]%s\007' "$percent" "$background")
fi

for foot_pid in $foot_pids; do
  children="/proc/$foot_pid/task/$foot_pid/children"
  if [[ -e $children ]]; then
    { child_pids=$(<"$children"); } 2>/dev/null || continue
  else
    # A kernel built without CONFIG_PROC_CHILDREN keeps no such list.
    child_pids=$(pgrep -P "$foot_pid")
  fi
  for child_pid in $child_pids; do
    tty=$(readlink "/proc/$child_pid/fd/1" 2>/dev/null)
    if [[ $tty == /dev/pts/* ]]; then
      printf '%b' "$foot_osc" >"$tty"
    fi
  done
done
