#!/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 within the rst directory. The pdf version of the
# documentation is only created, if the directory 'pdf' exists.

clear

# Check if required commands exist.., at least some of those.
# FOP and Saxon need Java
for cmd in capitalize htidy rst2man rst2html5 java fop gs manheader cpdf lower;
do
  if ! command -v "$cmd" &> /dev/null; then
    echo "Error: $cmd not found in PATH" >&2
    exit 1
  fi
done

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

# set to 0 to keep PDF version 1.4
MAKE_PDF_2=1

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

if [ -f ./version_* ]
then
  version=$(echo ./version_* | cut -d_ -f2)
fi

if [ -f ./section_* ]
then
  section=$(echo ./section_* | cut -d_ -f2)
fi

if [ -f ./category_* ]
then
  category=$(echo ./category_* | cut -d_ -f2)
fi

for rst in ./*.rst
do
  NAME=`basename "$rst" .rst`
  echo "$NAME"
  lower_name=$(lower "$NAME")
  MAN="../man/$lower_name.$section"
  # MAN=../man/`lower $NAME`.$section
  HTML="../html/$lower_name.html"
  CSS="../html/$lower_name.css"
  # optional
  PDFDIR="../pdf"
  DOCUTILS=$(docutils --version|cut -d '(' -f2|cut -d, -f1)
  echo -e "\t->creating $MAN"
  rst2man --rfc-references --title=`capitalize "$NAME"` ./"$rst" "$MAN"
  echo -e "\t->correcting man-page headers"
  manheader "$MAN" "$section" "$version" "$category"
  gzip -9 -f "$MAN"

  echo -e "\t->creating $HTML"
  rst2html5 --rfc-references --title=`capitalize "$NAME"` --xml-declaration --stylesheet="$CSS" ./"$rst" "$HTML"
  echo "--- calling HTML tidy -----" 
  htidy omit "$HTML"

  # create PDF if the pdf-directory exists.
  if [ -d $PDFDIR ]
  then
    PDF="$PDFDIR"/"$lower_name".pdf
    echo -e "\t->creating $PDF     ... This will take a while ...\n"

    # default style sheet for FOP
    XSL="$HOME/prog/html2Pdf.xsl"

    GS="Ghostscript $(gs --version)"
    FOP="FOP $(fop -v|cut -d ' ' -f3)"
    SAXON="Saxon 12.9"
    VIM="Vim $(vim --version | grep 'Vi IMproved' | cut -d ' ' -f5)"
    CPDF="$(cpdf -version|cut -d' ' -f1,4)"

    # may be used with cpdf, below.
    PMETA="$HOME/prog/m.xml"

    if [ -e "./stylesheet.xsl" ]
    then
      # The special style sheet should include html2Pdf.xsl,
      # hence the first two FOP_OPTS 
      #
      # ----> Unused when Saxon is called (see below)
      # export FOP_OPTS="-Djavax.xml.accessExternalStylesheet=all -Djavax.xml.accessExternalDTD=all" 
      # <------

      XSL="./stylesheet.xsl"

      echo "using project specific style sheet $XSL"
    fi


    # use FOP with the default XSL processor
    # create a first PDF file, name the config-file for font-embedding !
    # ~/bin/fop -c ~/bin/fop-2.11/fop/conf/fop.xconf -xml "$HTML" -xsl "$XSL" -pdf "$PDF"

    # Alternatively use FOP with the Saxon XSL processor.
    # ---> create a shell script, if you need this often or an alias for saxon.    
    FOOUT=/tmp/foout.fo
    echo "------- CALLING SAXON for html2FO --------"
    java -jar ~/bin/saxon-12.9/saxon-he-12.9.jar -s:"$HTML" -xsl:"$XSL" -o:"$FOOUT" loglevel='debug'

    echo "------- CALLING FOP for fo2PDF --------"
    fop -c ~/bin/fop-2.11/fop/conf/fop.xconf -fo "$FOOUT" -pdf "$PDF"
    #<-------

    # if PDF version 2.0 is wanted, do the conversion:
    if [ $MAKE_PDF_2 != 0 ]
    then
      PDF_2="$PDFDIR"/"$lower_name"_2.0.pdf
      echo "------- CALLING Ghostscript for PDF version 2 --------"
      /usr/local/bin/gs -dEmbedAllFonts=true -dSubsetFonts=false -dPDFSETTINGS=/prepress \
        -sDEVICE=pdfwrite -dOmitXMP=true -dCompatibilityLevel=2.0 \
        -dNOPAUSE -dBATCH -o "$PDF_2" "$PDF"

      if [ -e $PDF_2 ]
      then
        mv "$PDF_2" "$PDF"
      else
        echo -e "ERROR! PDF version 2.0 could NOT be created"
      fi

       # if project-specific metadata are needed consider
       # adding them here, add option
       # -set-metadata "$PMETA" \
       # before the final output -o 
      echo "------- CALLING cpdf and set meta data and compress --------"
      cpdf "$PDF" -set-creator "$VIM, $DOCUTILS" AND \
        -set-producer "$SAXON, $FOP, $GS, $CPDF" AND \
        -set-author "<michael.uplawski at uplawski.eu>"  AND \
        -compress AND \
        -squeeze AND \
        -set-title "$NAME manual" AND\
        -o "$PDF_2"

      if [ -e $PDF_2 ]
      then
        mv "$PDF_2" "$PDF"
      else
        echo -e "ERROR! Could not set PDF attributes."
      fi
    fi
  fi
done