#!/bin/sh

# Rebuild the two README previews from package-generated tutorial PDFs.
# First run build-examples.sh with a trusted external CoolProp shared library.
# Poppler's pdftoppm is needed only for regenerating these PNG previews.

set -eu

fail()
{
    printf 'error: %s\n' "$*" >&2
    exit 1
}

command -v pdftoppm >/dev/null 2>&1 \
    || fail 'pdftoppm is required (install Poppler)'

SCRIPT_DIR=$(CDPATH= cd -P "$(dirname "$0")" && pwd) \
    || fail 'could not locate the script directory'
PROJECT_DIR=$(CDPATH= cd -P "$SCRIPT_DIR/.." && pwd) \
    || fail 'could not locate the project directory'
IMAGE_DIR=$PROJECT_DIR/docs/images

for source_file in \
    "$PROJECT_DIR/tutorial/methane-linde-solution.pdf" \
    "$PROJECT_DIR/tutorial/butane-pv.pdf"; do
    [ -s "$source_file" ] \
        || fail "missing tutorial PDF: $source_file (run scripts/build-examples.sh first)"
done

TEMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/luacoolprop-readme-images.XXXXXX") \
    || fail 'could not create a temporary directory'
cleanup()
{
    rm -rf "$TEMP_DIR"
}
trap cleanup 0
trap 'exit 1' HUP INT TERM

mkdir -p "$IMAGE_DIR" || fail "could not create $IMAGE_DIR"

render_page()
{
    source_pdf=$1
    page=$2
    output_name=$3
    temporary_stem=$TEMP_DIR/$output_name

    pdftoppm -f "$page" -l "$page" -singlefile -r 140 -png \
        "$source_pdf" "$temporary_stem" \
        || fail "could not render page $page of $source_pdf"
    [ -s "$temporary_stem.png" ] \
        || fail "page $page produced no PNG: $source_pdf"
    mv -f "$temporary_stem.png" "$IMAGE_DIR/$output_name.png" \
        || fail "could not install $output_name.png"
    printf '%s\n' "$IMAGE_DIR/$output_name.png"
}

render_page "$PROJECT_DIR/tutorial/methane-linde-solution.pdf" 6 \
    methane-linde-cycle
render_page "$PROJECT_DIR/tutorial/butane-pv.pdf" 3 \
    butane-pv-ideal-gas
