#!/usr/bin/env bash
# "apt dla fontów": Google Fonts ZIP → GitHub (ofl RAW) → fonts.gstatic.com → mirrory.
# System-wide install do /usr/local/share/fonts/fontget/<rodzina> + fc-cache.
# Usage: sudo ./fontget.sh "IM Fell English SC" "Cinzel Decorative" "EB Garamond"

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: $1"; }
need fc-cache
command -v wget >/dev/null 2>&1 || command -v curl >/dev/null 2>&1 || die "Need wget/curl"
command -v unzip >/dev/null 2>&1 || warn "unzip missing — ZIP installs limited"
command -v file  >/dev/null 2>&1 || warn "file missing — MIME checks limited"
command -v fc-list >/dev/null 2>&1 || die "Missing: fc-list"

fetch(){ local u="$1" o="$2"; if command -v wget >/dev/null 2>&1; then wget -O "$o" --https-only --no-verbose "$u"; else curl -L --fail --show-error --output "$o" "$u"; fi; }
slug(){ echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g'; }
present(){ fc-list -f '%{family}\n' | tr ',' '\n' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' | tr '[:upper:]' '[:lower:]' | sort -u | grep -Eiq "$1"; }

install_dir="/usr/local/share/fonts/fontget"; $SUDO mkdir -p "$install_dir"

is_zip(){ command -v file >/dev/null 2>&1 && file "$1" | grep -qi zip; }
gf_zip_try(){
  local name="$1" outdir="$2" enc zip
  enc="$(python3 - <<PY
import urllib.parse,sys
print(urllib.parse.quote(sys.argv[1]))
PY
"$name")" || enc="$(echo "$name" | sed 's/ /%20/g')"
  zip="$(mktemp /tmp/fontget.XXXXXX.zip)"
  if fetch "https://fonts.google.com/download?family=${enc}" "$zip"; then
    if is_zip "$zip"; then $SUDO mkdir -p "$outdir"; $SUDO unzip -o -q "$zip" -d "$outdir" || true; rm -f "$zip"; return 0; fi
  fi
  rm -f "$zip" || true; return 1
}
gh_ofl_try(){
  local family="$1" outdir="$2" html
  html="$(mktemp /tmp/ofl.$(slug "$family").html)"
  if fetch "https://github.com/google/fonts/tree/main/ofl/$(slug "$family")" "$html"; then
    mapfile -t paths < <(grep -Eo '/google/fonts/blob/main/ofl/'"$(slug "$family")"'/[^"]+\.(ttf|otf)' "$html" | sed 's|/blob/|/raw/|g' | sort -u)
    [ "${#paths[@]}" -gt 0 ] || { rm -f "$html"; return 1; }
    $SUDO mkdir -p "$outdir"
    for p in "${paths[@]}"; do fetch "https://github.com$p" "$outdir/$(basename "$p")" || true; done
    rm -f "$html"; return 0
  fi
  rm -f "$html"; return 1
}
gstatic_try(){ local out="$2"; shift 2; for u in "$@"; do fetch "$u" "$out" && [ -s "$out" ] && return 0; done; return 1; }

report(){ local label="$1" re="$2"; if present "$re"; then printf "RESULT: %-24s : OK\n" "$label"; else printf "RESULT: %-24s : FAIL\n" "$label"; fi }

if [ $# -lt 1 ]; then echo "Usage: $0 <Font Family> [Another ...]"; exit 1; fi

for family in "$@"; do
  echo; log "=== $family ==="
  fam_slug="$(slug "$family")"
  outdir="$install_dir/$fam_slug"
  $SUDO mkdir -p "$outdir"

  case "$fam_slug" in
    cinzel-decorative|cinzel|cinzel-decorative-black)
      fetch "https://github.com/google/fonts/raw/main/ofl/cinzeldecorative/CinzelDecorative-Black.ttf" "$outdir/CinzelDecorative-Black.ttf" || warn "Cinzel fetch failed"
      ;;
    im-fell-english-sc)
      gstatic_try "$fam_slug" "$outdir/IMFeENsc.ttf" \
        "https://fonts.gstatic.com/s/imfellenglishsc/v7/h3Tn6yWfw4b5qaLD1RWvz5ATixNthKRRR1XVH3rJNiw.ttf" \
        "https://fonts.gstatic.com/s/imfellenglishsc/v6/h3Tn6yWfw4b5qaLD1RWvz5ATixNthKRRR1XVH3rJNiw.ttf" \
      || { fetch "https://github.com/google/fonts/raw/main/ofl/imfellenglishsc/IMFeENsc28P.ttf" "$outdir/IMFeENsc.ttf" || true
           [ -s "$outdir/IMFeENsc.ttf" ] || fetch "https://github.com/google/fonts/raw/main/ofl/imfellenglishsc/IMFellEnglishSC-Regular.ttf" "$outdir/IMFeENsc.ttf" || true
           [ -s "$outdir/IMFeENsc.ttf" ] || fetch "https://www.wfonts.com/download/data/2016/06/14/im-fell-english-sc/IMFeENsc28P.ttf" "$outdir/IMFeENsc.ttf" || true
           [ -s "$outdir/IMFeENsc.ttf" ] || fetch "https://www.1001freefonts.com/d/6800/IMFeENsc28P.ttf" "$outdir/IMFeENsc.ttf" || true; }
      ;;
    eb-garamond|ebgaramond)
      # Najpierw apt (jeśli chcesz: sudo apt install fonts-ebgaramond), tu tylko web:
      gf_zip_try "$family" "$outdir" || gh_ofl_try "$family" "$outdir" || true
      ;;
    *)
      gf_zip_try "$family" "$outdir" || gh_ofl_try "$family" "$outdir" || true
      ;;
  esac

  $SUDO find "$outdir" -type f -size 0 -print -delete || true
  $SUDO find "$outdir" -type f \( -name "*.ttf" -o -name "*.otf" \) -exec chmod 0644 {} \; || true
  $SUDO find "$outdir" -type d -exec chmod 0755 {} \; || true
  $SUDO fc-cache -f -v >/dev/null || true

  case "$fam_slug" in
    cinzel* )            report "Cinzel Decorative"   '^cinzel decorative( |$)' ;;
    im-fell-english-sc ) report "IM Fell English SC"  '^im fell english sc( |$)' ;;
    eb-garamond* )       report "EB Garamond"         '^eb garamond( |$)' ;;
    * )                  report "$family"             "$(echo "$family" | tr '[:upper:]' '[:lower:]' | sed 's/ /.* /g')" ;;
  esac
done

echo; log "All done."
