#!/bin/bash
# Install the Omarchy-rendered Thunderbird theme into every Thunderbird profile.
# The CSS is rendered from ~/.config/omarchy/themed/thunderbird.css.tpl.
# Thunderbird reads it at startup, so a running Thunderbird picks up a theme
# change after a restart.

CSS="$HOME/.local/state/omarchy/current/theme/thunderbird.css"
TB_DIR="$HOME/.config/thunderbird"
IMPORT='@import "omarchy-theme.css";'
PREF='user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true);'

[[ -f $CSS && -f $TB_DIR/profiles.ini ]] || exit 0

grep -E '^Path=' "$TB_DIR/profiles.ini" | cut -d= -f2- | while read -r path; do
  [[ $path = /* ]] || path="$TB_DIR/$path"
  [[ -d $path ]] || continue

  mkdir -p "$path/chrome"
  cp "$CSS" "$path/chrome/omarchy-theme.css"

  # @import must come first in userChrome.css; keep anything else already there.
  chrome="$path/chrome/userChrome.css"
  if ! grep -qxF "$IMPORT" "$chrome" 2>/dev/null; then
    {
      echo "$IMPORT"
      if [[ -f $chrome ]]; then cat "$chrome"; fi
    } >"$chrome.tmp" && mv "$chrome.tmp" "$chrome"
  fi

  # Thunderbird only loads userChrome.css with this pref enabled.
  grep -qF "$PREF" "$path/user.js" 2>/dev/null || echo "$PREF" >>"$path/user.js"
done
