#!/bin/bash

# creates a man-page and a HTML-page (optionally also a PDF) from the rst-files
# in the current directory.
#
# Other than calls to the utilities which do the transformation of one
# file-format into another, this script calls a Ruby-routine ’manheader‘, which
# completes the man-page header, where the docutils component ’rst2man‘ does
# not honor all the available fields, notably 
#
# *) The program version
# *) The creation date of the man-page
# *) The section number and global header (here called ’Category‘)
#
# Missing field values have to be present in the current directory, alongside
# the original RST-file, in the form of otherwise empty files, named according
# to a simple pattern:
#
# version_[version-number], e.g. version_1.2
# section_[section-number], e.g. section_6 for the man-page to a game
# category_[header], e.g. category_Games\ Manual for the man-page to a game
# 
# The script does not inform about missing values but ignores them and creates
# a man-page without them.
#
# Furthermore, to put the resulting documentation in the right subdirectories,
# you should provide the directories man, html and optionally pdf alongside the
# directory, which contains the original *.rst file, e.g.:
#
# doc
#   |________________
#   |     |    |     |
#   rst   man  html  pdf
#
# Call make_doc from whithin the rst-directory. The pdf-version of the
# documentation is only created, if the directory 'pdf' exists.

version=''
section=''
category=''
prog=`basename "$0"`

if [ "$1" == "-h" -o "$1" == "--help" ]
then
  echo -e "\n\tusage: $prog"
  exit 0
fi

if [ -f ./version_* ]
then
  version=`ls version_* | cut -d_ -f2` 
fi

if [ -f ./section_* ]
then
  section=`ls section_* | cut -d_ -f2`
fi

if [ -f ./category_* ]
then
  category=`ls category_* | cut -d_ -f2`
fi

for rst in ./*.rst
do
  NAME=`basename "$rst" .rst`
  echo "$NAME"
  MAN=../man/`lower $NAME`.$section
  HTML=../html/`lower $NAME`.html
  # optional
  PDFDIR=../pdf
  PDF="$PDFDIR"/`lower $NAME`.pdf

  rst2man --title=`capitalize "$NAME"` ./"$rst" "$MAN"
  rst2html --title=`capitalize "$NAME"` ./"$rst" "$HTML"
  if [ -d $PDFDIR ]
  then
    man -Tpdf "$MAN" > "$PDF"
  fi
  manheader "$MAN" "$section" "$version" "$category"
  gzip -9 -f "$MAN"
done
