#!/usr/bin/env bash
set -euo pipefail

if [ $# -ne 1 ]; then
  echo "Usage: $0 <band-number>"
  exit 1
fi

NUM=$1

# Filenames based on band number
PDF="echolot_band_${NUM}.pdf"
OCR_PDF="echolot_band_${NUM}_OCR.pdf"
TXT="band_${NUM}.txt"
FLOW_MD="band_${NUM}_flow.md"
EPUB="echolot_band_${NUM}.epub"

# 1. Combine JPGs → PDF
echo ">>> Creating PDF from JPGs..."
img2pdf $(ls -v *.JPG) -o "$PDF"

# 2. OCR with sidecar TXT
echo ">>> Running OCR..."
ocrmypdf --language deu --deskew --clean --sidecar "$TXT" \
  --jobs 4 --optimize 1 "$PDF" "$OCR_PDF"

# 3. Convert TXT → Markdown
echo ">>> Converting TXT to Markdown..."
pandoc "$TXT" -f markdown -t markdown -o "$FLOW_MD" --wrap=none

# 4. Markdown → EPUB
echo ">>> Creating EPUB..."
pandoc "$FLOW_MD" -o "$EPUB" \
  --metadata title="Echolot Band ${NUM}" \
  --metadata author="Walter Kempowski"

echo ">>> Done: $EPUB"
