#!/usr/bin/env bash
# Build the resume: regenerate the .docx from resume.json, render a .pdf via
# OnlyOffice's headless x2t converter, and ENFORCE a hard 3-page maximum.
# Exits non-zero (and deletes the stale PDF) if the render exceeds MAX_PAGES.
set -euo pipefail

cd "$(dirname "$0")"

MAX_PAGES=3
DOCX="Phillip_Tarrant_Resume_$(date +%Y).docx"
PDF="Phillip_Tarrant_Resume_$(date +%Y).pdf"

OO=/opt/onlyoffice/desktopeditors
X2T="$OO/converter/x2t"
# Font cache generated by the OnlyOffice desktop app (x2t needs it; the bundled
# converter ships without one and crashes otherwise).
FONTS="$HOME/.local/share/onlyoffice/desktopeditors/data/fonts"

# --- 1. Generate the .docx from resume.json ---
node generate_resume.js

# --- 2. Render .docx -> .pdf via x2t ---
if [[ ! -x "$X2T" ]]; then
  echo "ERROR: OnlyOffice x2t not found at $X2T — cannot render/verify pages." >&2
  exit 3
fi
if [[ ! -f "$FONTS/AllFonts.js" ]]; then
  echo "ERROR: OnlyOffice font cache missing at $FONTS/AllFonts.js." >&2
  echo "       Open the OnlyOffice desktop app once to generate it, then re-run." >&2
  exit 3
fi

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
cat > "$TMP/conv.xml" <<XML
<?xml version="1.0" encoding="utf-8"?>
<TaskQueueDataConvert xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <m_sFileFrom>$PWD/$DOCX</m_sFileFrom>
  <m_sFileTo>$PWD/$PDF</m_sFileTo>
  <m_nFormatTo>513</m_nFormatTo>
  <m_sFontDir>$FONTS</m_sFontDir>
  <m_sAllFontsPath>$FONTS/AllFonts.js</m_sAllFontsPath>
  <m_sThemeDir>$OO/editors/sdkjs/slide/themes</m_sThemeDir>
  <m_sTempDir>$TMP</m_sTempDir>
</TaskQueueDataConvert>
XML

( cd "$OO/converter" && LD_LIBRARY_PATH="$OO/converter:$OO" "$X2T" "$TMP/conv.xml" )

# --- 3. Enforce the page limit ---
PAGES="$(pdfinfo "$PDF" | awk '/^Pages:/ {print $2}')"
echo "Rendered $PDF — $PAGES page(s)."
if (( PAGES > MAX_PAGES )); then
  echo "ERROR: resume is $PAGES pages, exceeds the $MAX_PAGES-page limit. Trim content." >&2
  rm -f "$PDF"
  exit 1
fi
echo "OK: within the $MAX_PAGES-page limit. Built $DOCX and $PDF."
