#!/bin/bash
# Convert a PDF into a raster-image PDF for older Acrobat versions.
# Usage: ./pdfconv DPI input.pdf output.pdf

set -eu

if [ "$#" -ne 3 ]; then
    echo "Usage: $0 DPI input.pdf output.pdf" >&2
    exit 1
fi

DPI="$1"
INPUT="$2"
OUTPUT="$3"

case "$DPI" in
    ''|*[!0-9]*|0)
        echo "ERROR: DPI must be a positive integer." >&2
        exit 1
        ;;
esac

if [ ! -f "$INPUT" ]; then
    echo "ERROR: Input PDF not found: $INPUT" >&2
    exit 1
fi

for cmd in gs python3; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "ERROR: Required command not found: $cmd" >&2
        exit 1
    fi
done

TMPDIR_CONV=$(mktemp -d)
trap 'rm -rf "$TMPDIR_CONV"' EXIT HUP INT TERM

echo "Input: $INPUT"
echo "Output: $OUTPUT"
echo "Raster resolution: $DPI DPI"
echo "Rendering pages to GIF..."

gs -q -dSAFER -dBATCH -dNOPAUSE \
    -dUseCropBox \
    -sDEVICE=gif8 \
    -r"$DPI" \
    -sOutputFile="$TMPDIR_CONV/page-%04d.gif" \
    "$INPUT"

python3 - "$TMPDIR_CONV" "$OUTPUT" "$DPI" <<'PY'
import os
import sys
import glob
from PIL import Image
from reportlab.pdfgen import canvas

directory, output, dpi = sys.argv[1], sys.argv[2], int(sys.argv[3])
pages = sorted(glob.glob(os.path.join(directory, "page-*.gif")))

if not pages:
    raise SystemExit("ERROR: Ghostscript did not produce any GIF pages.")

temporary_output = os.path.join(directory, "output.tmp")

pdf = canvas.Canvas(
    temporary_output,
    pdfVersion=(1, 2),
    pageCompression=1
)

for filename in pages:
    with Image.open(filename) as image:
        width_px, height_px = image.size

    width_pt = width_px * 72.0 / dpi
    height_pt = height_px * 72.0 / dpi

    pdf.setPageSize((width_pt, height_pt))
    pdf.drawImage(
        filename, 0, 0,
        width=width_pt,
        height=height_pt
    )
    pdf.showPage()

pdf.save()

import shutil

destination_tmp = output + ".tmp"
shutil.copy2(temporary_output, destination_tmp)
os.replace(destination_tmp, output)

print("Converted", len(pages), "pages.")
PY

echo "Checking generated PDF..."

gs -q -dBATCH -dNOPAUSE -sDEVICE=nullpage "$OUTPUT"

echo "Checking PDF version..."
head -c 8 "$OUTPUT"
echo

echo "Conversion complete: $OUTPUT"
ls -lh "$OUTPUT"
