#!/bin/sh
#
# SYNOPSIS
#
# make_summary DOC-FILES...
#
# DESCRIPTION
#
# Produce a summary file from all the documentation files listed.
# A summary is the first paragraph of the documentation file.
# It can be produced with the `make_summaries` script.
#
# ENVIRONMENT_VARIABLES
#
# - SUMMARY_FILE
#
# (For portability, stick to POSIX shell constructs in this script.)
#

set -e

SUMMARY_FILE=${SUMMARY_FILE:-summaries}

SPLIT_API_DOCS=$(dirname "$0")/split_api_docs

delete_leading_trailing_blanks() {
    # From http://student.northpark.edu/pemente/sed/sed1line.txt
    # delete all leading blank lines at top of file
    # delete all trailing blank lines at end of file
    sed -e '/./,$!d' \
        -e :a -e '/^\n*$/{$d;N;ba' -e '}'
}

if test $# -eq 0
then
    echo "Usage: make_summary DOC-FILES..." 1>&2
    exit 1
fi

TEMPDIR=make_summaries.tmp.$$_$RANDOM
mkdir $TEMPDIR
trap 'rm -rf $TEMPDIR' 0 1 2 3 13 15

awk -f "$SPLIT_API_DOCS" $TEMPDIR "$@"

for file in $TEMPDIR/*
do
    name=$(basename "$file")
    echo "Found $name" 1>&2

    sed -n '1,/^$/ p' $file |           # print first paragraph
    delete_leading_trailing_blanks |
    sed -e "s/^/$name: /"               # add prefix
done > $SUMMARY_FILE

if test ! -s $SUMMARY_FILE
then
    echo "WARNING: $SUMMARY_FILE is empty." 1>&2
fi

# vim: set et:
