#!/usr/bin/env bash
# Build the cover letter: <source>.yaml -> cover-letter.html -> PDF.
#
#   bash profile/build-cover-letter-pdf.sh
#   bash profile/build-cover-letter-pdf.sh applications/cleo/cover-letter.yaml
#
# The PDF gets a full timestamp in its name and lands in /mnt/storage/inbox
# (visible via https://files.udalovs.ru); a stable cover-letter.pdf copy points
# at the latest build. Nothing binary is written into the repository.
#
# A local font is used (profile/assets/fonts/Inter-Variable.ttf); the generated
# HTML points at it relatively, so the temporary print copy is written next to
# the HTML (same directory) instead of /tmp.
set -euo pipefail

cd "$(dirname "$0")/.."

DATA="${1:-profile/cover-letter.yaml}"
INBOX="${INBOX:-/mnt/storage/inbox}"
OUT_DIR="$(dirname "$DATA")"

if [[ ! -f "$DATA" ]]; then
  echo "ERROR: cover letter source not found: $DATA" >&2
  exit 1
fi

# 1) regenerate HTML + Markdown from the single source
python3 profile/cover-letter-build.py --data "$DATA" --out-dir "$OUT_DIR"

HTML="${OUT_DIR}/cover-letter.html"

# 2) inject the build time (invisible in the PDF, kept in the page source).
#    The temp copy stays in OUT_DIR so the relative font URL still resolves.
GEN="$(date -u +'%Y-%m-%d %H:%M:%S UTC')"
TMP="${OUT_DIR}/.cover-letter-build-$$.html"
trap 'rm -f "$TMP"' EXIT
sed -e "s/__GEN_STAMP__/${GEN}/" "$HTML" > "$TMP"

# 3) render the PDF directly to the inbox (no local copy - never commit binaries).
#    profile/cover-letter.yaml       -> cover-letter.pdf
#    applications/cleo/cover-letter.yaml -> cleo-cover-letter.pdf
STAMP="$(date +%Y%m%d-%H%M%S)"
PARENT="$(basename "$OUT_DIR")"
if [[ "$PARENT" == "profile" ]]; then
  BASE="cover-letter"
else
  BASE="${PARENT}-cover-letter"
fi
OUT="${BASE}-${STAMP}.pdf"
LATEST="${BASE}.pdf"

playwright pdf --paper-format A4 "file://$(realpath "$TMP")" "$INBOX/${OUT}"
cp -f "$INBOX/${OUT}" "$INBOX/${LATEST}"

echo "OK:"
echo "  source: $DATA"
echo "  inbox : $INBOX/${OUT}"
echo "  latest: $INBOX/${LATEST}"
echo "  web   : https://files.udalovs.ru/${OUT}"
