#!/bin/sh -e
#
# SYNOPSIS
#
# make_page [OPTIONS...] INPUT-FILE... [--] [PANDOC-OPTIONS...]
#
# OPTIONS
#
# --protos FILE
# --postprocess latex
# --postprocess texinfo
#
# DESCRIPTION
#
# Preprocess input files before passing onto Pandoc.
# Input files may contain sections written as (with one or more hashes):
#
#       # API: foo
#
# In each case, the prototype or type declaration for `foo` will be inserted
# in place.  These come from $PROTOS which can be generated with another
# script.
#
# ENVIRONMENT VARIABLES
#
# - PANDOC
# - PROTOS
#
# (For portability, stick to POSIX shell constructs in this script.)
#

PANDOC=${PANDOC:-pandoc}
PROTOS=${PROTOS:-protos}

# Passed down to preprocess_page.awk
export PROTOS

# Speed up utilities.
export LC_ALL=C

PREPROCESS_PAGE=$(dirname "$0")/preprocess_page.awk

POSTPROCESS=
POSTPROCESS_LATEX=$(dirname "$0")/postprocess_latex.awk
postprocess_texinfo() {
    # Replace dummy references by real references (see make_dummy_refs
    # script).
    sed 's/@uref{DUMMY_REF,/@ref{/g'
}

# main

while true; do
    case $1 in
        --protos)
            PROTOS=$2
            shift 2
            ;;
        --postprocess)
            case $2 in
                latex)
                    POSTPROCESS=latex
                    shift 2
                    ;;
                texinfo)
                    POSTPROCESS=texinfo
                    shift 2
                    ;;
                *)
                    echo "make_page: wrong --postprocess argument: $2" 1>&2
                    exit 1
                    ;;
            esac
            ;;
        *)
            break
            ;;
    esac
done

if test ! -f "$PROTOS"
then
    echo "Error: $PROTOS file not found."
    exit 1
fi

TEMPFILE=make_page.tmp.$$_$RANDOM
trap 'rm -f "$TEMPFILE"' 0 1 2 3 13 15

while true; do
    case $1 in
        --)
            shift
            break
            ;;
        -*|'')
            break
            ;;
        *)
            cat "$1" >> "$TEMPFILE"
            echo >> "$TEMPFILE"
            shift
            ;;
    esac
done

awk -f "$PREPROCESS_PAGE" "$TEMPFILE" | "$PANDOC" "$@"

# Stop now if post-processing is not required.
test -n "$POSTPROCESS" || exit 0

# Pandoc options to figure out where the output went.
OUTPUT=
while test $# -gt 0
do
    case $1 in
        -o|--output) OUTPUT=$2 ; shift ;;
        -o*)         OUTPUT=${1#-o} ;;
        --output=*)  OUTPUT=${1#--output=} ;;
    esac
    shift
done

# For simplicity, we only support post-processing if the output went to a file.
test -n "$OUTPUT" || exit 0

case $POSTPROCESS in
    latex)   awk -f "$POSTPROCESS_LATEX" ;;
    texinfo) postprocess_texinfo ;;
esac < "$OUTPUT" > "$TEMPFILE"
cat < "$TEMPFILE" > "$OUTPUT"

# vim: set et:
