#!/bin/bash
# ─────────────────────────────────────────────────────────────
# ISO27DIY eBook build script
# Run from: my-vault/iso27DIY-mkII/marketing/eBook-Audit/
# cd path/to/my-vault/iso27DIY-mkII/marketing/eBook-Audit && bash build.sh
# ─────────────────────────────────────────────────────────────

set -e

# ── CONFIG ────────────────────────────────────────────────────
SOURCE="ebook-iso27001-audit.md"  # Your Markdown source file
OUTPUT="ISO27DIY-ebook.pdf"       # Output PDF name
TEMPLATE="iso27diy-book.tex"      # LaTeX template

# ── COLORS FOR OUTPUT ─────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}Building ISO27DIY eBook...${NC}"
echo "  Source:   $SOURCE"
echo "  Output:   $OUTPUT"
echo ""

# ── CHECK DEPENDENCIES ────────────────────────────────────────
command -v pandoc >/dev/null 2>&1 || {
  echo -e "${RED}Error: pandoc not found. Run: brew install pandoc${NC}"
  exit 1
}
command -v xelatex >/dev/null 2>&1 || {
  echo -e "${RED}Error: xelatex not found. Run: brew install --cask mactex${NC}"
  exit 1
}

# ── BUILD ─────────────────────────────────────────────────────
pandoc "$SOURCE" \
  --template="$TEMPLATE" \
  --pdf-engine=xelatex \
  --pdf-engine-opt=-shell-escape \
  --toc \
  --toc-depth=2 \
  --syntax-highlighting=tango \
  --from=markdown+smart+footnotes+definition_lists \
  -V documentclass=report \
  --output="$OUTPUT"

# ── DONE ──────────────────────────────────────────────────────
if [ -f "$OUTPUT" ]; then
  SIZE=$(du -sh "$OUTPUT" | cut -f1)
  echo -e "${GREEN}Done! → $OUTPUT ($SIZE)${NC}"
  # Open the PDF automatically
  open "$OUTPUT"
else
  echo -e "${RED}Build failed. Check the output above for errors.${NC}"
  exit 1
fi