#!/usr/bin/env bash
# System-wide install & verify (Debian/RPi):
#  - EB Garamond (APT)
#  - Cinzel Decorative Black (RAW TTF)
#  - IM Fell English SC (gstatic/RAW)
# No TeX build here. Very verbose + clear final report.

set -Eeuo pipefail

SUDO=sudo; [ "$(id -u)" -eq 0 ] && SUDO=
log(){ echo -e "[+] $*"; }
warn(){ echo -e "[WARN] $*" >&2; }
die(){ echo -e "[FATAL] $*" >&2; exit 1; }

need(){ command -v "$1" >/dev/null 2>&1 || die "Missing tool: $1"; }
fetch(){
  local url="$1" out="$2"
  if command -v wget >/dev/null 2>&1; then
    log "wget -> $url"
    wget -O "$out" --https-only --no-verbose "$url"
  else
    log "curl -> $url"
    curl -L --fail --show-error --output "$out" "$url"
  fi
}

# ---- detection using fc-list families (robust, no PCRE) ----
fc_families_lower() {
  fc-list -f '%{family}\n' \
  | tr ',' '\n' \
  | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' \
  | tr '[:upper:]' '[:lower:]' \
  | sort -u
}
has_family_re() {  # $1 = POSIX ERE anchored-at-start pattern (lowercase)
  fc_families_lower | grep -Eiq "$1"
}

# ---- prereqs ----
for t in fc-cache fc-list grep sed awk; do need "$t"; done
command- v wget >/dev/null 2>&1 || command -v curl >/dev/null 2>&1 || die "Need wget or curl"

SYSTEM_DIR="/usr/local/share/fonts/dj"
DIR_CINZEL="$SYSTEM_DIR/cinzel-decorative"
DIR_IMFELL="$SYSTEM_DIR/im-fell-english-sc"
$SUDO mkdir -p "$DIR_CINZEL" "$DIR_IMFELL"

echo "=== APT phase (EB Garamond) ==="
if command -v apt-get >/dev/null 2>&1; then
  $SUDO apt-get update -y || warn "apt update failed (continuing)"
  if $SUDO apt-get install -y --no-install-recommends fonts-ebgaramond; then
    log "installed: fonts-ebgaramond"
  else
    warn "apt install failed: fonts-ebgaramond"
  fi
else
  warn "apt-get not found — skipping"
fi

echo
log "Families BEFORE web fallback (sample grep):"
fc-list | grep -Ei "Garamond|Cinzel|Fell" || echo "  (none)"

echo
echo "=== Web fallback (system-wide to $SYSTEM_DIR) ==="

# --- Cinzel Decorative Black ---
CINZEL_TTF="$DIR_CINZEL/CinzelDecorative-Black.ttf"
if ! has_family_re '^cinzel decorative( |$)'; then
  fetch "https://github.com/google/fonts/raw/main/ofl/cinzeldecorative/CinzelDecorative-Black.ttf" "$CINZEL_TTF" || warn "Cinzel Decorative Black download failed"
  [ -s "$CINZEL_TTF" ] && $SUDO chmod 0644 "$CINZEL_TTF"
else
  log "Cinzel Decorative already present."
fi

# --- IM Fell English SC ---
IMFELL_TTF="$DIR_IMFELL/IMFeENsc.ttf"
if ! has_family_re '^im fell english sc( |$)'; then
  # Try known gstatic TTFs (stable direct links)
  for u in \
    "https://fonts.gstatic.com/s/imfellenglishsc/v7/h3Tn6yWfw4b5qaLD1RWvz5ATixNthKRRR1XVH3rJNiw.ttf" \
    "https://fonts.gstatic.com/s/imfellenglishsc/v6/h3Tn6yWfw4b5qaLD1RWvz5ATixNthKRRR1XVH3rJNiw.ttf"
  do
    if fetch "$u" "$IMFELL_TTF"; then
      [ -s "$IMFELL_TTF" ] && { $SUDO chmod 0644 "$IMFELL_TTF"; log "IM Fell SC from gstatic OK"; break; }
    fi
  done
  # Secondary RAW in google/fonts (names changed over time)
  if [ ! -s "$IMFELL_TTF" ]; then
    for u in \
      "https://github.com/google/fonts/raw/main/ofl/imfellenglishsc/IMFeENsc28P.ttf" \
      "https://github.com/google/fonts/raw/main/ofl/imfellenglishsc/IMFellEnglishSC-Regular.ttf"
    do
      if fetch "$u" "$IMFELL_TTF"; then
        [ -s "$IMFELL_TTF" ] && { $SUDO chmod 0644 "$IMFELL_TTF"; log "IM Fell SC from google/fonts RAW OK"; break; }
      fi
    done
  fi
  # Minimal mirror fallback (only if naprawdę trzeba)
  if [ ! -s "$IMFELL_TTF" ]; then
    for u in \
      "https://www.wfonts.com/download/data/2016/06/14/im-fell-english-sc/IMFeENsc28P.ttf" \
      "https://www.1001freefonts.com/d/6800/IMFeENsc28P.ttf"
    do
      fetch "$u" "$IMFELL_TTF" || true
      [ -s "$IMFELL_TTF" ] && { $SUDO chmod 0644 "$IMFELL_TTF"; log "IM Fell SC from mirror OK"; break; }
    done
  fi
  [ -s "$IMFELL_TTF" ] || warn "IM Fell English SC still missing."
else
  log "IM Fell English SC already present."
fi

echo
log "Fix perms & rebuild cache..."
$SUDO find "$SYSTEM_DIR" -type f -size 0 -print -delete || true
$SUDO find "$SYSTEM_DIR" -type f \( -name "*.ttf" -o -name "*.otf" \) -exec chmod 0644 {} \; || true
$SUDO find "$SYSTEM_DIR" -type d -exec chmod 0755 {} \; || true
$SUDO fc-cache -f -v >/dev/null || warn "fc-cache returned non-zero"

# ---- FINAL REPORT ----
echo
log "FINAL STATUS (fc-list families & file presence)"
families="$(fc_families_lower)"

report(){
  local label="$1" fam_re="$2" file_hint="$3"
  local fam_ok file_ok="n/a"
  if echo "$families" | grep -Eiq "$fam_re"; then fam_ok="OK"; else fam_ok="MISSING"; fi
  if [ -n "$file_hint" ]; then
    if [ -s "$file_hint" ]; then file_ok="yes"; else file_ok="no"; fi
  fi
  printf "  %-22s : families=%-8s file=%-3s  (%s)\n" "$label" "$fam_ok" "$file_ok" "${file_hint:-no-file-hint}"
}

report "EB Garamond"           '^eb garamond( |$)'           ""                 # from APT
report "Cinzel Decorative"     '^cinzel decorative( |$)'      "$CINZEL_TTF"
report "IM Fell English SC"    '^im fell english sc( |$)'     "$IMFELL_TTF"

echo
log "Done. (Run your LaTeX pipeline next.)"
