#!/usr/bin/env bash
# Convert a modern PDF to PDF 1.2 for older PDF viewers such as Acrobat 3.
# Usage: pdf12 input.pdf [output.pdf]
set -Eeuo pipefail

usage() {
    echo "Usage: pdf12 input.pdf [output.pdf]" >&2
    echo "Converts a PDF to PDF 1.2 (Acrobat 3-era compatibility)." >&2
}

if [[ $# -lt 1 || $# -gt 2 ]]; then
    usage
    exit 2
fi

input=$1
if [[ ! -f "$input" || ! -r "$input" ]]; then
    echo "Error: cannot read input file: $input" >&2
    exit 1
fi

if ! command -v gs >/dev/null 2>&1; then
    echo "Error: Ghostscript is not installed." >&2
    echo "Install it with: sudo apt update && sudo apt install ghostscript" >&2
    exit 1
fi

if [[ $# -eq 2 ]]; then
    output=$2
else
    dir=$(dirname -- "$input")
    base=$(basename -- "$input")
    stem=${base%.*}
    [[ "$stem" == "$base" ]] && stem=$base
    output="$dir/${stem}-acrobat3.pdf"
fi

if [[ "$input" -ef "$output" ]]; then
    echo "Error: output must not be the same file as the input." >&2
    exit 1
fi

if [[ -e "$output" ]]; then
    echo "Error: output already exists: $output" >&2
    echo "Choose another output filename; the original will not be overwritten." >&2
    exit 1
fi

# Write to a temporary file first, so a failed conversion won't leave a
# partially written final output.
outdir=$(dirname -- "$output")
outfile=$(basename -- "$output")
tmp=$(mktemp "$outdir/.${outfile}.tmp.XXXXXX")
cleanup() { rm -f -- "$tmp"; }
trap cleanup EXIT

if ! gs -q -dSAFER -dBATCH -dNOPAUSE \
    -sDEVICE=pdfwrite \
    -dCompatibilityLevel=1.2 \
    -dPDFSETTINGS=/prepress \
    -dAutoRotatePages=/None \
    "-sOutputFile=$tmp" \
    "$input"; then
    echo "Error: Ghostscript could not convert this PDF." >&2
    exit 1
fi

if [[ ! -s "$tmp" ]]; then
    echo "Error: conversion produced an empty file." >&2
    exit 1
fi

# Confirm the generated file advertises PDF 1.2 before installing it.
version=$(head -c 8 "$tmp" | tr -d '\r\n')
if [[ "$version" != "%PDF-1.2" ]]; then
    echo "Warning: output header is '$version', not %PDF-1.2." >&2
fi

mv -- "$tmp" "$output"
trap - EXIT
echo "Created: $output"
echo "PDF header: $(head -c 8 "$output" | tr -d '\r\n')"
echo "Note: inspect the converted file; complex modern features may be simplified."
