#!/usr/bin/env bash
# epubmake -- full EPUB creation pipeline with metadata + validation
set -euo pipefail
usage() {
echo "Usage: epubmake <input.md> [--title TITLE] [--author AUTHOR] [--cover cover.jpg]"
exit 1
}
[ $# -lt 1 ] && usage
input="$1"; shift
title="" author="" cover="" output=""
while [ $# -gt 0 ]; do
case "$1" in
--title) title="$2"; shift 2 ;;
--author) author="$2"; shift 2 ;;
--cover) cover="$2"; shift 2 ;;
--output|-o) output="$2"; shift 2 ;;
*) echo "Unknown option: $1"; usage ;;
esac
done
[ -z "$output" ] && output="${input%.md}.epub"
args=(-t epub3 --toc --toc-depth=2)
[ -n "$title" ] && args+=(--metadata "title=$title")
[ -n "$author" ] && args+=(--metadata "author=$author")
[ -n "$cover" ] && args+=(--epub-cover-image="$cover")
echo "Building EPUB: $output"
# Handle single file or directory of chapters
if [ -d "$input" ]; then
chapters=$(ls "$input"/*.md 2>/dev/null | sort -V)
[ -z "$chapters" ] && { echo "No .md files in $input"; exit 1; }
pandoc $chapters "${args[@]}" -o "$output"
else
pandoc "$input" "${args[@]}" -o "$output"
fi
echo "Created: $output ($(du -h "$output" | cut -f1))"
# Validate if epubcheck is available
if command -v epubcheck &>/dev/null; then
echo ""
echo "Validating..."
epubcheck "$output" 2>&1 | tail -5
elif command -v python3 -c "import epubcheck" &>/dev/null 2>&1; then
python3 -c "from epubcheck import EpubCheck; r = EpubCheck('$output'); print('Valid' if r.valid else 'INVALID')"
else
echo "(epubcheck not installed, skipping validation)"
fi