#!/bin/bash
#
# Copyright (C) 2011,2012 Frank Sundermeyer <fsundermeyer@opensuse.org>
#
# Author:
# Frank Sundermeyer <fsundermeyer@opensuse.org>
#
# daps = DocBook Authoring and Publishing Suite


VERSION=1.1.4

# autoconf replaces @foo@ stuff with ${prefix}/.. if @foo@ has not
# explicitly been set, so we need to at least export prefix to
# be on the safe side

export prefix=/usr

# ----------------------------------------------------------------------------
# VARIABLES
#
# First, list all variables we need to pass to make. They all need to be
# EXPORTED, but we do not want to write the export statement in the config
# files, so we need to have this list
#
# IMPORTANT
# All variables that need to be exported for further use in the makefiles
# need to be added here!!
#


# PENDING:
# DISTVER, PRODUCTNAME, and PRODUCTNAMEREG are only need for resolving the
# suse-PIs. Once we get rid of that, remove these variables fom the list
#

declare -a VARLIST
VARLIST=(
    DISTVER
    PRODUCTNAME
    PRODUCTNAMEREG
    ASPELL_EXTRA_DICT
    ASPELL_LANG
    ASPELL_SKIP_TAGS
    BUILD_DIR
    CB_OPTIONS
    COLOR
    COMMENTS
    COMMENT_STR
    CONF_PREFIX
    CONVERT_OPTS
    DEBUG
    DOC_DIR
    DAPSROOT
    DAPSROOT_DEFAULT
    DEF_FILE
    DESKTOPFILES
    DEVEL
    DIA_OPTIONS
    DOCBOOK5_RNC_SCHEME
    DOCCONF
    DOCCONF_DEFAULT
    DOCUMENTFILES
    DRAFT
    DRAFT_STR
    EPUBCHECK
    EPUB_CSS
    EXPORT_DIR
    FALLBACK_STYLEROOT
    FOP_CONFIG_FILE
    FOP_OPTIONS
    FOP_WRAPPER
    FORMATTER
    GZIP_MAN
    HTML4
    HTML_CSS
    HTMLROOT
    IMG_VIEWER
    INCLUDE_MANIFEST
    INK_OPTIONS
    JING_FLAGS
    LIB_DIR
    LIBEXEC_DIR
    MAIN
    NOPDF
    NOSET
    PAGEFILES
    PDFNAME
    PROFARCH
    PROFCONDITION
    PROFILE_URN
    PROFOS
    PROFVENDOR
    REMARKS
    REMARK_STR
    SETDATE
    STATIC_HTML
    ROOTID
    STYLEDEVEL
    STYLEROOT
    USEMETA
    WH_SEARCH
    VERBOSITY
    XEP_CONFIG_FILE
    XEP_OPTIONS
    XEP_WRAPPER
    XSLTPARAM
)
# unset all for a fresh start, but preserve $DOCCONF - it might have been set
# by having sourced a DC-file

[[ -n $DOCCONF ]] && DOCCONF_SAVE=$DOCCONF
unset "${VARLIST[@]}"
[[ -n $DOCCONF_SAVE ]] && DOCCONF=$DOCCONF_SAVE


# VARLIST contains all variables that can be set via config or command line.
#
# The following UNSETLIST contains variables local to this script
# unfortunately  

# To be on the safe side, we also want to unset a few variables before we start
# because they are used/defined in make or may cause other harm if accidentally
# set
#
declare -a UNSETLIST
UNSETLIST=(
    DOC_DIR_CMDL
    BIN_DIR
    BUILD_DIR_CMDL
    COLOR_CMDL
    CONFIG
    DC_PATH_EXISTS
    DOCCONF_CMDL
    DAPSROOT_CMDL
    FALLBACK_STYLEROOT_CMDL
    LOG_DIR
    MAIN_CMDL
    R_DIR
    STYLEROOT_CMDL
    VERBOSITY_CMDL 
)
unset "${UNSETLIST[@]}"

# PATHLIST contains all variables holding a path. Relative paths need to be 
# made absolute and we need this list in order to know which variables hold
# path information

declare -a PATHLIST
PATHLIST=(
    BUILD_DIR
    DAPSROOT
    DOCCONF_DEFAULT
    EPUB_CSS
    FALLBACK_STYLEROOT
    FOP_CONFIG_FILE
    FOP_WRAPPER
    HTML_CSS
    STYLEDEVEL
    STYLEROOT
    XEP_CONFIG_FILE
    XEP_WRAPPER
)

# ----------------------------------------------------------------------------
# We need to set some basic defaults outside of $DEFAULT_CONFIG

# this script's name
ME=$(basename $0)

# default config file
DEFAULT_CONFIG="/etc/daps/config"

# The default DAPSROOT 
DAPSROOT_DEFAULT="/usr/share/daps"

# default libdir
DEFAULT_LIB_DIR="${DAPSROOT_DEFAULT}/lib"
DEFAULT_LIBEXEC_DIR="${DAPSROOT_DEFAULT}/libexec"

# user config file
USER_CONFIG="$HOME/.daps/config"

#---------------------------------------------------
# SUBCOMMANDS
#
# Fake Associative Array (for bash 3 compatibility)
#  Key   = subcommand
#  Value = function call (from lib/daps_functions)
# 
# use VALUE=$(arrayGet "ARRAYNAME" "KEY") to get the value
# arrayGet returns 1 if KEY was not found
#
## The subcommands can be executed using eval:
##   eval "${SUBCOMMANDS[$SUBCMD]} $SUBCMD ${SCMD_ARGS[@]}"
## Using such an array rather than a function to call the subcommands has got
## the advantage that we can very easily check whether a subcommand is valid
## or not by just testing if ${SUBCOMMANDS[$SUBCMD]} is set

declare -a SUBCOMMANDS
SUBCOMMANDS+=("all=build_pdfs")
SUBCOMMANDS+=("bigfile-reduced=build_generic")
SUBCOMMANDS+=("bigfile=build_generic")
SUBCOMMANDS+=("check=no_opts")
SUBCOMMANDS+=("checklink=checklink")
SUBCOMMANDS+=("chklink=checklink")
SUBCOMMANDS+=("clean-all=no_opts")
SUBCOMMANDS+=("clean-images=no_opts")
SUBCOMMANDS+=("clean-results=no_opts")
SUBCOMMANDS+=("clean=no_opts")
SUBCOMMANDS+=("color-pdf-name=show_names")
SUBCOMMANDS+=("color-pdf=build_pdfs")
SUBCOMMANDS+=("db2novdoc=build_generic")
SUBCOMMANDS+=("debug=build_generic")
SUBCOMMANDS+=("desktop-files-dir-name=show_names")
SUBCOMMANDS+=("desktop-files=build_generic")
SUBCOMMANDS+=("dist-all=profile_first")
SUBCOMMANDS+=("dist-book=build_generic")
SUBCOMMANDS+=("dist-desktop-files=build_generic")
SUBCOMMANDS+=("dist-document-files-html=build_generic")
SUBCOMMANDS+=("dist-document-files-pdf=build_generic")
SUBCOMMANDS+=("dist-graphics-png=build_generic")
SUBCOMMANDS+=("dist-graphics=build_generic")
SUBCOMMANDS+=("dist-html-name=show_names")
SUBCOMMANDS+=("dist-html-single=build_generic")
SUBCOMMANDS+=("dist-html=build_generic")
SUBCOMMANDS+=("dist-htmlsingle=build_generic")
SUBCOMMANDS+=("dist-jsp=build_generic")
SUBCOMMANDS+=("dist-xml=build_generic")
SUBCOMMANDS+=("dist=build_generic")
SUBCOMMANDS+=("document-files-dir-name=show_names")
SUBCOMMANDS+=("document-files-html=build_generic")
SUBCOMMANDS+=("document-files-pdf=build_generic")
SUBCOMMANDS+=("epub-name=show_names")
SUBCOMMANDS+=("epub=build_epub")
SUBCOMMANDS+=("force=build_pdfs")
SUBCOMMANDS+=("getimages=getimages")
SUBCOMMANDS+=("html-dir-name=show_names")
SUBCOMMANDS+=("html-single-name=show_names")
SUBCOMMANDS+=("html-single=build_html_jsp")
SUBCOMMANDS+=("html=build_html_jsp")
SUBCOMMANDS+=("htmlsingle-name=show_names")
SUBCOMMANDS+=("htmlsingle=build_html_jsp")
SUBCOMMANDS+=("jana=checklink")
SUBCOMMANDS+=("jsp-dir-name=show_names")
SUBCOMMANDS+=("jsp=build_html_jsp")
SUBCOMMANDS+=("locdrop=build_locdrop")
SUBCOMMANDS+=("man=build_man")
SUBCOMMANDS+=("missinggraphics=filelists")
SUBCOMMANDS+=("nothing=no_opts")
SUBCOMMANDS+=("offspring=no_opts")
SUBCOMMANDS+=("online-docs=online-docs")
SUBCOMMANDS+=("online-localized=online-docs")
SUBCOMMANDS+=("optipng=build_generic")
SUBCOMMANDS+=("package-html=packaging")
SUBCOMMANDS+=("package-jsp=packaging")
SUBCOMMANDS+=("package-pdf=packaging")
SUBCOMMANDS+=("package-src-name=show_names")
SUBCOMMANDS+=("package-src=packaging")
SUBCOMMANDS+=("package=packaging")
SUBCOMMANDS+=("pdf-color-name=show_names")
SUBCOMMANDS+=("pdf-color=build_pdfs")
SUBCOMMANDS+=("pdf-name=show_names")
SUBCOMMANDS+=("pdf=build_pdfs")
SUBCOMMANDS+=("penguin=no_opts")
SUBCOMMANDS+=("productinfo=build_generic")
SUBCOMMANDS+=("prof=build_generic")
SUBCOMMANDS+=("profile=build_generic")
SUBCOMMANDS+=("profiledir=comments_remarks")
SUBCOMMANDS+=("projectfiles=filelists")
SUBCOMMANDS+=("projectgraphics=filelists")
SUBCOMMANDS+=("provide-color-images=build_generic")
SUBCOMMANDS+=("provide-epub-images=build_generic")
SUBCOMMANDS+=("provide-images=build_generic")
SUBCOMMANDS+=("real-clean=no_opts")
SUBCOMMANDS+=("remainingfiles=filelists")
SUBCOMMANDS+=("remaininggraphics=filelists")
SUBCOMMANDS+=("showenv=showenv")
SUBCOMMANDS+=("showvariable=profile_first")
SUBCOMMANDS+=("spellcheck=spellcheck")
SUBCOMMANDS+=("text=build_generic")
SUBCOMMANDS+=("text-name=show_names")
SUBCOMMANDS+=("txt=build_generic")
SUBCOMMANDS+=("txt-name=show_names")
SUBCOMMANDS+=("validate=comments_remarks")
SUBCOMMANDS+=("warn-images=filelists")
SUBCOMMANDS+=("webhelp=webhelp")
SUBCOMMANDS+=("webhelp-dir-name=show_names")
SUBCOMMANDS+=("wiki-name=show_names")
SUBCOMMANDS+=("wiki=build_generic")
SUBCOMMANDS+=("xmlfiles=filelists")
SUBCOMMANDS+=("xmlgraphics-bw=filelists")
SUBCOMMANDS+=("xmlgraphics=filelists")

#---------------------------------------------------
# HELP texts for subcommands
#
# Fake associative array with
#  Key   = subcommand
#  Value = help text
# 

declare -a HELP_SUBCOMMAND 
    
HELP_SUBCOMMAND+=("all=Build a color PDF document from the XML sources.")
HELP_SUBCOMMAND+=("bigfile-reduced=Creates a single XML file (bigfile) from the MAIN-file referenced in the\nDC-file or specified on the command line starting at the given rootid\nby following all xi:includes.")
HELP_SUBCOMMAND+=("bigfile=Creates a single XML file (bigfile) from the MAIN-file referenced in the\nDC-file or specified on the command line by following all xi:includes.\nA rootid parameter is ignored.")
HELP_SUBCOMMAND+=("check=DEBUGGING: Shows a list of internal variables and their values.")
HELP_SUBCOMMAND+=("checklink=Validates ftp and http(s) links in XML sources.")
HELP_SUBCOMMAND+=("chklink=Validates ftp and http(s) links in XML sources.")
HELP_SUBCOMMAND+=("clean-all=Removes all data (documents, images, logfiles, profiled XML, ...) generated\nby DAPS.")
HELP_SUBCOMMAND+=("clean-images=Removes the results of all image conversions generated by DAPS.")
HELP_SUBCOMMAND+=("clean-results=Removes all generated documents and logfiles for a given DC- or MAIN-file.\nImage conversion results and profiled XML sources will not be deleted.")
HELP_SUBCOMMAND+=("clean=Removes all profiled XML sources and temporary files generated by DAPS.")
HELP_SUBCOMMAND+=("color-pdf-name=Print the file name that would result when building a color PDF.")
HELP_SUBCOMMAND+=("color-pdf=Build a color PDF document from the XML sources.")
HELP_SUBCOMMAND+=("db2novdoc=Converts DocBook4 XML sources to NovDoc (a subset of DocBook4).")
HELP_SUBCOMMAND+=("debug=DEBUGGING: Reserved for adding debug targets")
HELP_SUBCOMMAND+=("desktop-files-dir-name=Print the directory name that would result when building KDE desktop files.")
HELP_SUBCOMMAND+=("desktop-files=Create desktop files for KDE.")
HELP_SUBCOMMAND+=("dist-all=Creates tar archives with source graphics, source XML, and the resulting\nHTML build. Also builds a color PDF document.")
HELP_SUBCOMMAND+=("dist-book=Creates a tar archive with the XML sources specified by rootid.\nNOTE: Graphics are not included and the unpacked sources may not validate.\n      To create tarballs containing images and a complete, valid set\n      of XML sources, use the command 'package-src'.")
HELP_SUBCOMMAND+=("dist-desktop-files=Create a tar archive with desktop files for KDE.")
HELP_SUBCOMMAND+=("dist-document-files-html=Create a tar archive with document files for an HTML document referenced\nin the GNOME help system.")
HELP_SUBCOMMAND+=("dist-document-files-pdf=Create document files for a PDF document referenced in the GNOME help system.")
HELP_SUBCOMMAND+=("dist-graphics-png=Create a tar archive with all images from the set referenced\nin the DC- or the MAIN-file. All images will be converted to PNG.")
HELP_SUBCOMMAND+=("dist-graphics=Create a tar archive with all images from the set referenced in the\nDC- or the MAIN-file. Images will be included in their 'native'\nformat.")
HELP_SUBCOMMAND+=("dist-html-name=Print the file name that would result when building a distributable tar archive\nof an HTML document.")
HELP_SUBCOMMAND+=("dist-html-single=Print the file name that would result when building a distributable tar archive\nof a single file HTML document.")
HELP_SUBCOMMAND+=("dist-html=Creates a distributable tar archive of an HTML document (including images).")
HELP_SUBCOMMAND+=("dist-htmlsingle=Creates a distributable tar archive of a single file HTML document\n(including images).")
HELP_SUBCOMMAND+=("dist-jsp=Creates a distributable tar archive of a JSP document (including images).")
HELP_SUBCOMMAND+=("dist-xml=Creates a tar archive with the XML sources specified by The MAIN file.\nNOTE: Graphics are not included and the unpacked sources may not validate.\n      To create tarballs containing images and a complete, valid set of\n      XML sources, use the command 'package-src'.")
HELP_SUBCOMMAND+=("document-files-dir-name=Print the directory name that would result when building\nGNOME document files.")
HELP_SUBCOMMAND+=("document-files-html=Create document files for an HTML document referenced in the GNOME help system.")
HELP_SUBCOMMAND+=("document-files-pdf=Create document files for a PDF document referenced in the GNOME help system.")
HELP_SUBCOMMAND+=("epub-name=Print the file name that would result when building an eBook.")
HELP_SUBCOMMAND+=("epub=Build an eBook from the XML sources.")
HELP_SUBCOMMAND+=("getimages=List and/or display images (in a viewer of your choice) referenced in an\nXML file or by rootid.")
HELP_SUBCOMMAND+=("html-dir-name=Print the directory name that would result when building an HTML book.")
HELP_SUBCOMMAND+=("html-single-name=Print the file name that would result when building a single file HTML document.")
HELP_SUBCOMMAND+=("html-single=Build a single file HTML document from the XML sources.")
HELP_SUBCOMMAND+=("html=Build an HTML document from the XML sources.")
HELP_SUBCOMMAND+=("htmlsingle-name=Print the file name that would result when building a single file HTML book.")
HELP_SUBCOMMAND+=("htmlsingle=Build a single file HTML document from the XML sources.")
HELP_SUBCOMMAND+=("jana=Validates ftp and http(s) links in XML sources.")
HELP_SUBCOMMAND+=("jsp-dir-name=Print the file name that would result when building a JSP document.")
HELP_SUBCOMMAND+=("jsp=Build a JSP document from the XML sources.")
HELP_SUBCOMMAND+=("locdrop=Create all tar archives required to distribute a complete set for translation.\nRequires SVN hosting of the sources - files that need to be translated\nhave to be marked with the property doc:trans=yes.")
HELP_SUBCOMMAND+=("man=Build one or more man pages from suitable XML sources. All <refentry> parts\nfrom the source file(s) will be transformed to man pages.")
HELP_SUBCOMMAND+=("missinggraphics=Prints a list of images that are referenced in the XML sources but are missing\nin the images' source directory.")
HELP_SUBCOMMAND+=("nothing=DEBUGGING: Benchmarking target.")
HELP_SUBCOMMAND+=("offspring=")
HELP_SUBCOMMAND+=("online-docs=Creates a bigfile for the complete set, a tarball including all referenced\ngraphics in PNG format, color-pdf and epub builds as well as an archive with\na single-html build.")
HELP_SUBCOMMAND+=("online-localized=")
HELP_SUBCOMMAND+=("optipng=Reduce the size of the source PNG images using 'optipng'.\nNOTE: This command will directly alter your source images!")
HELP_SUBCOMMAND+=("package-html=Create all archives and files needed for packaging an HTML document.")
HELP_SUBCOMMAND+=("package-jsp=Create all archives and files needed for packaging a JSP document.")
HELP_SUBCOMMAND+=("package-pdf=Create all archives and files needed for packaging a color PDF document.")
HELP_SUBCOMMAND+=("package-src-name=Print the file name that would result when building a distributable source\narchive.")
HELP_SUBCOMMAND+=("package-src=Creates a distributable source archive containg the sources of the complete set\nincluding the images.")
HELP_SUBCOMMAND+=("pdf-color-name=Print the file name that would result when building a color PDF.")
HELP_SUBCOMMAND+=("pdf-color=Build a color PDF document from the XML sources.")
HELP_SUBCOMMAND+=("pdf-name=Print the file name that would result when building a grayscale PDF document.")
HELP_SUBCOMMAND+=("pdf=Build a grayscale PDF document from the XML sources (with cropmarks if using\nthe XEP formatter).")
HELP_SUBCOMMAND+=("penguin=")
HELP_SUBCOMMAND+=("productinfo=Print the contents of the tags <productname> and <productnumber for the given ROOTID")
HELP_SUBCOMMAND+=("prof=Create profiled souces from the original XML sources. If the MAIN-file does\nnot contain profiling instructions, link the files into the profile directory.")
HELP_SUBCOMMAND+=("profile=Create profiled souces from the original XML sources. If the MAIN-file does\nnot contain profiling instructions, link the files into the profile directory.")
HELP_SUBCOMMAND+=("profiledir=Print the directory name that would result when profiling the XML sources.")
HELP_SUBCOMMAND+=("projectfiles=Print a list of all project files (XML sources, entity declarations, DC-file)\nused by the document referenced by the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("projectgraphics=Print a list of all source image used in the document referenced\nby the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("provide-color-images=Convert all image files used in the document referenced by the DC- or MAIN-file.\nAll files will be converted to PNG, '.dia', '.eps', and '.fig' files\nwill also be converted into SVG and PDF. '.svg' files  will also\nbe converted into PDF.")
HELP_SUBCOMMAND+=("provide-epub-images=Prepare converted images for inclusion into an eBook.")
HELP_SUBCOMMAND+=("provide-images=Convert all image files used in the document referenced by the DC- or MAIN-file\nto grayscale. All files will be converted to PNG, '.dia', '.eps', and\n'.fig' files will also be converted into SVG and PDF. '.svg' files  will\nalso be converted into PDF.")
HELP_SUBCOMMAND+=("real-clean=Removes all data (documents, images, logfiles, profiled XML, ...) generated\nby DAPS")
HELP_SUBCOMMAND+=("remainingfiles=Print a list of all source XML files _not_ used in the document referenced\nby the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("remaininggraphics=Print a list of all source images _not_ used in the document referenced\nby the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("showenv=DEBUGGING: Target reserved for daps-docmanager")
HELP_SUBCOMMAND+=("showvariable=DEBUGGING: Show the value of a given variable.\nUsage: showvariable VARIABLE=<VARNAME>")
HELP_SUBCOMMAND+=("spellcheck=Spellchecks the file specified with --file or the document specified by rootid.")
HELP_SUBCOMMAND+=("text=Build an ASCII text document the from the XML sources.")
HELP_SUBCOMMAND+=("text-name=Print the file name that would result when building an ASCII text document.")
HELP_SUBCOMMAND+=("txt=Build am ASCII text document the from the XML sources.")
HELP_SUBCOMMAND+=("txt-name=Print the file name that would result when building an ASCII text document.")
HELP_SUBCOMMAND+=("validate=Validate the profiled XML sources referenced by the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("warn-images=Print a list of source images with non-unique names.")
HELP_SUBCOMMAND+=("webhelp=Build an HTML document with a table of contents/search frame (aka webhelp)\nfrom the XML sources.")
HELP_SUBCOMMAND+=("webhelp-dir-name=Print the directory name that would result when building a webhelp document.")
HELP_SUBCOMMAND+=("wiki=Build a MediaWiki document from the XML sources. Images need to be uploaded\nmanually to the Wiki.")
HELP_SUBCOMMAND+=("wiki-name=Print the file name that would result when building a MediaWiki document.")
HELP_SUBCOMMAND+=("xmlfiles=Print a list of all XML files used in the document referenced\nby the DC- or MAIN-file.")
HELP_SUBCOMMAND+=("xmlgraphics=Print the list of generated images that will directly be used\nwhen building a document.")
HELP_SUBCOMMAND+=("xmlgraphics-bw=Print the list of generated grayscale images that will directly be used\nwhen building a document.")


# ----------------------------------------------------------------------------
# FUNCTIONS
#
# We need to declare a few basic funtions first because they are needed
# immideately. All other functions can be found at
# $DAPSROOT/lib/daps-functions
# ---------
# Help
#

function daps_help () {
    echo "
Usage:
  1. $ME -d DC-file [--options] <subcommand> [--subcommand-options]
  2. $ME -m MAIN file [--options] <subcommand> [--subcommand-options]


Global Options:
  --builddir=BUILD_DIR      Directory where every output $ME generates will end
                            up
                            Default: <doc dir>/build/$BOOK
  --color=(0|1)             By default errors, results, warnings and certain
                            info messages are printed in color using bash color
                            codes. Set to '0' to turn off colors.
                            Default: 1 (when the output does not go to a
                                        terminal, colored output will be
                                        disabled automatically)
  --debug                   Print debugging messages. Far more verbose than the
                             --verbosity options
  --docconfig=DC-file,
  -d DC-file                Path to doc config file to use. Mandatory
                            unless there is only a single DC-file in the current
                            directory or unless you have configured a default
                            value (DOCCONF_DEFAULT) in $USER_CONFIG.
                            Note: Options --docconfig and --main exclude
                                  each other.
  --fb_styleroot            Fallback styleroot directory. Can only be used in
                            conjunction with --styleroot. By default, the
                            DocBook stylesheets are used as a fallback if
                            custom styles for an output format are  not present.
                            With this option you can specify an alternative
                            fallback. Useful if you have forks of your custom
                            stylesheets. The DocBook stylesheets will be used
                            as a last resort.
                            Specify only the file name, not an absolute path.
  --help, -h                Help
  --main, -m                Path to the main file defining your document.
                            Note: Options --main and --docconfig exclude
                                  each other.
  --styleroot               By default, daps uses the DocBook Stylesheets to
                            create output. If you have your own set of
                            stylesheets, specify the absolute path to the
                            stylesheet directory here. The DocBook stylesheets
                            will be used as a fallback in case styles are not
                            defined for all output formats.
  --verbosity=0, -v0        Verbosity Level 0 (print 1 line of results)
  --verbosity=1, -v1, -v    Verbosity Level 1 (print intermediate results)
  --verbosity=2, -v2, -vv   Verbosity Level 2 (print all commands, very verbose)

  --version                 Print version number

  
Subcommands:
   help                       Print this help

  Generate Books:
    color-pdf, pdf-color      Color pdf book
    epub                      ePUB book
    html                      HTML book
    html-single, htmlsingle   Single file HTML book
    jsp                       JSP book
    man                       man pages
    pdf                       grayscale pdf (with cropmarks when using XEP)
    txt, text                 ASCII book
    webhelp                   HTML book with collapsable TOC and search
    wiki                      Single file MediaWiki book


  Create Distributable Archives:
    dist-all                  Shortcut for running the subcommands 'validate'
                              'checklink' 'dist-xml' 'dist-html' 'dist' and
                              'color-pdf'
    dist-book                 Profiled XML sources of the book
    dist-graphics             Graphics (PNG, SVG) of the whole set
    dist-graphics-png         PNG graphics of the whole set. SVG graphics are
                              converted to PNG
    dist-html                 HTML and graphics
    dist-htmlsingle           Single-file HTML and graphics
    dist-jsp                  JSP and graphics
    dist-xml                  Profiled XML sources of the whole set. Identical
                              to dist-book when using a book rather than a set.
    locdrop                   Provide everything that is needed to translate a
                              set

  File lists:
    projectfiles              Print project files (XML sources, entity
                              declarations, DC-file) used by the book
    projectgraphics           Print source graphics used by the book
    missinggraphics           Print missing images
    remainingfiles            Print XML source files _not_ used by the book
    remaininggraphics         Print source graphics _not_ used by the book
    warn-images               Print a list of non-unique image files
    xmlfiles                  Print XML source files used by the book
    xmlgraphics               Print (generated) color graphics really used to
                              generate the books
    xmlgraphics-bw            Print (generated) grayscale graphics really used
                              to generate the books

  Cleaning up:
    clean                     Remove all profiled sources and temporary files
    clean-images              Remove all generated images
    clean-results             Remove all generated books, archives, and log
                              files. Generated images and profiled sources will
                              _not_ be deleted.
    clean-all, real-clean     Remove everything generated by $ME

  Packaging:
    package-html              Provide HTML tarball (set), desktop and document
                              files (for KDE and GNOME)
    package-jsp               Provide JSP tarball
    package-pdf               Provide color pdf, desktop and document files
                              (for KDE and GNOME)
    package-src               Provide profiled XML sources and graphics

  Deploying:
    online-docs               Provide a profiled XML bigfile, a graphics
                              tarball (PNG only), color-pdf, epub, and
                              a single-html archive.

  Other Commands:
    checklink                 Linkchecker for links from <ulink> tags
    db2novdoc                 Convert DocBook XML sources to NovDoc
    getimages                 List or display images from a profiled DocBook
                              XML file
    optipng                   Optimize (size) source PNGs
    profile, prof             Profile XML sources
    spellcheck                Spellchecks the file specified with --file or the
                              document specified by rootid.
    validate                  Validate profiled sources. Automatically profiles
                              the XML sources if needed

  File and Directory Names:
    <target>-name             Print resulting file name for <target>. <target>
                              may be one of color-pdf, epub, html-single,
                              pdf, txt
    <target>-dir-name         Print resulting directory name for <target>.
                              <target> may be either html or jsp

  Debugging:
    check                     Print a list of the most important make variables
                              and their value
    profiledir                Print the profiling directory currently used
    showvariable              Print value of a given make variable:
                              $ME showvariable VARIABLE=<MAKE_VARIABLE>

Type '$ME <subcommand> -h' for help on a specific subcommand.
"
}

#    online-localized          Provide a profiled XML bigfile and a graphics
#                              tarball (PNG only). All xrefs to other books from
#                              the set are replaced by ulinks pointing to
#                              <?provo dirname?>/id plus text like \"See book
#                              FOO, chapter BAR\" Useful for delivering
#                              translated manuals, when only part of the set
#                              has been translated


# ---------
# Verbose error handling
#
function exit_on_error () {
    echo -e "ERROR: ${1}" >&2
    exit 1;
}

# ---------
# Associative Array emulation
#
# Since older distributions still have bash 3, we cannot use associative arrays
# (a bash 4 feature). The following function returns the value of a list value
# of the following form:  ARRAYNAME=( "KEY=VALUE" )
# The key/value pair is just a string in a regular array (aka list). Contrary to
# other associative array emulations, this method allows to have key names with
# characters forbidden for bash variables (such as "-")
#
# How to call   : VALUE=$(arrayGet "ARRAYNAME" "KEY")
# Return  values: 0 if key was found
#                 1 if key was not found
#
function arrayGet {
    local ARRAYNAME COMPARE KEY VALUE
    ARRAYNAME=$1[@]
    KEY=$2
    for VALUE in "${!ARRAYNAME}"; do
        COMPARE=${VALUE%%=*}
        if [[ $COMPARE = $KEY ]]; then
            echo ${VALUE#*=}
            return 0
        fi
    done
    # KEY not found
    return 1
}

# ---------
# Get absolute path, remove trailing / and test if path is valid
#
function sanitize_path () {
    # Takes values
    # $1 = path
    # $2 = variable name holding $1
    # $3 = additional base dir for $1 (optional)
    #
    # sets absolute path without trailing / for $1, links are being followed
    # also tests if paths are valid 
    #
    # in case of a non-existing path, returns 2 if variablename matches
    # _WRAPPER, else returns 1
    #
    local ABSPATH BASEDIR MYPATH VARNAME
    
    MYPATH=$1
    VARNAME=$2
    [[ -n $3 ]] && BASEDIR=$3

    # Do nothing if $1 is an empty value
    [[ -z $MYPATH ]] && return
    
    # ignore values that need to be set by configure
    # (makes it possible to directly use a SVN checkout)
    [[ $MYPATH =~ @[a-zA-Z]*@ ]] && return

    # 1. Remove trailing Slash
    #
    MYPATH=${MYPATH%/} # remove trailing slash

    if [[ "/" != ${MYPATH:0:1} ]]; then
        [[ -n $BASEDIR ]] && MYPATH="${BASEDIR}/${MYPATH}"
        ABSPATH=$(readlink -en "$MYPATH")
        if [[ 0 = $? ]]; then
            eval "$VARNAME=$ABSPATH"
        else
            if [[ $VARNAME =~ _WRAPPER ]]; then
                # issue warnings only for FOP_WRAPPER and XEP_WRAPPER
                # if path does not exist
                echo "HINT: $VARNAME=$MYPATH: Path does not exist"
            else
                # exit for all other variables if MYPATH is invalid
                exit_on_error "$VARNAME=$MYPATH: Path does not exist"
            fi
        fi
    else
        # path is already absolute, set to MYPATH (because of having cut
        # the trailing /
        eval "$VARNAME=$MYPATH"
    fi
}

# ----------------------
# Check all paths in $PATHLIST with sanitize_path
#
function check_pathlist () {
    local ABS BASEDIR DIR VAL

    BASEDIR=$1

    for DIR in ${PATHLIST[@]}; do
        eval "VAL=\$$DIR"
        if [[ -n $VAL ]]; then
            sanitize_path "$VAL" "$DIR" "$BASEDIR"
        fi
    done
}

# ---------
# Try to automatically get the DOCCONF
#
function autoset_docconf () {
    # if there is only one DOCCONF file in the current directory, use it
    # and also set DOC_DIR
    #
    local DC_FILENAME DC_PARENT DC_REAL_PATH DC_REAL_DIR
    declare -a DC_COUNT
    DC_COUNT=( $(find -L . -maxdepth 1 -name "${CONF_PREFIX}*" -type f) )
    if [[ 1 = ${#DC_COUNT[@]} ]]; then
        # There is only one DOCCONF file
        #
        # two possibilites:
        # 1. We are already in DOC_DIR
        # 2. We are in the documents build result directory
        # (DOC_DIR/build/<name>), where daps creates a link to the
        # real ENV file
        if [[ -h ${DC_COUNT[0]} ]]; then
            # DOCCONF is a link
            DC_REAL_PATH=$(readlink -nm "${DC_COUNT[0]}")
            DC_REAL_DIR=$(dirname "$DC_REAL_PATH")
            DC_FILENAME=$(basename "$DC_REAL_PATH")
            DC_PARENT=${DC_FILENAME#${CONF_PREFIX}*}
            if [[ -e ${DC_REAL_DIR}/build/${DC_PARENT}/$DC_FILENAME ]]; then
                # we are in the result dir - set DOCCONF to the
                # real path (with links "resolved")
                DOCCONF_CMDL="$DC_REAL_PATH"
            else
                # we are in DOC_DIR
                # preserve links
                DOCCONF_CMDL="${PWD}/${DC_COUNT[0]}"
            fi
        else
            # no link, we are in DOC_DIR
            sanitize_path "${DC_COUNT[0]}" "DOCCONF_CMDL"
        fi
        # set DOC_DIR
        DOC_DIR=$(dirname "$DOCCONF_CMDL")
        if [[ 1 -le $VERBOSITY ]]; then
            echo "Using automatically detected DOCCONF $DOCCONF_CMDL"
        fi
    else
        # more than one or no DOCCONF
        exit_on_error "Could not find a valid MAIN file.\nPlease specify either a DOCCONF or a MAIN file at the command line"
    fi
}

# ---------
# Set MAIN to an absolute path
#

function set_mainfile () {
    local MAINFILE
    MAINFILE="$1"
    if [[ -e "$MAINFILE" ]]; then
        # MAINFILE is a file or link
        sanitize_path "$MAINFILE" "MAIN_CMDL"
        if [[ -z "$DOC_DIR" ]]; then
            DOC_DIR=$(dirname "$MAIN_CMDL")
            DOC_DIR=${DOC_DIR%/xml*} #remove xml directory
        fi
    else
        if [[ -e "xml/$MAINFILE" ]]; then
            # MAIN is not a valid file, but ./xml/$MAIN exists
            sanitize_path "xml/$MAINFILE" "MAIN_CMDL"
            if [[ -z "$DOC_DIR" ]]; then
                DOC_DIR="$PWD"
            fi
            if [[ 1 -le $VERBOSITY ]]; then
                echo "Using MAIN file $MAIN_CMDL"
            fi
        else
            if [[ -n $DOC_DIR ]]; then
                if [[ -e "${DOC_DIR}/xml/$MAINFILE" ]]; then
                    MAIN_CMDL="${DOC_DIR}/xml/$MAINFILE"
                elif [[ -e "${DOC_DIR}/$MAINFILE" ]]; then
                    MAIN_CMDL="${DOC_DIR}/$MAINFILE"
                else
                    exit_on_error "Fatal error: ${DOC_DIR}/xml/$MAINFILE does not exist."
                fi
            else
               exit_on_error "Fatal error: ${PWD}/$MAINFILE does not exist."
            fi
        fi
    fi
}


# ---------
# Recover command-line values
#
function recover_cmdl_values () {
    test -n "$BUILD_DIR_CMDL" && BUILD_DIR="$BUILD_DIR_CMDL"
    test -n "$COLOR_CMDL"     && COLOR="$COLOR_CMDL"
    test -n "$DOCCONF_CMDL"   && DOCCONF="$DOCCONF_CMDL"
    test -n "$DAPSROOT_CMDL"  && DAPSROOT="$DAPSROOT_CMDL"
    test -n "$FALLBACK_STYLEROOT_CMDL" && FALLBACK_STYLEROOT="$FALLBACK_STYLEROOT_CMDL"
    test -n "$MAIN_CMDL"      && MAIN="$MAIN_CMDL"
    test -n "$STYLEROOT_CMDL" && STYLEROOT="$STYLEROOT_CMDL"
    test -n "$VERBOSITY_CMDL" && VERBOSITY="$VERBOSITY_CMDL"
}

# ----------------------------------------------------------------------------
# Parsing the command line arguments with GNU getopt
#
# In order to separate general daps parameters from subcommand parameters,
# we are setting POSIXLY_CORRECT before parsing the first time.
# This causes getopt to interprete all remaining parameters as non-option
# parameters as soon as the first non-option parameter (the subcommand) is
# found. This value must be _exported_

export POSIXLY_CORRECT=1

# So, the first getopt go will parse all parameters listed directly after the 
# daps command, leaving an array ($@) with the subcommand and it's
# parameters, which can be parsed in a second getopt go.

#-------------------------------
# Parsing the daps parameters
#
# If variables such as $BUILD_DIR, $DOCCONF, and $DAPSROOT are set via command
# line switch, we do not want to overwrite them by any other file we source
# at a later stage (command line always wins).
# Declaring the variables as readonly is unfortunately not an option, since 
# every attempt to (un)set a read-only variable throws an error - something
# we do not want when sourcing a config-file.
# Therefore we need to save each variable twice in order to recover the
# original value.

ARGS=$(getopt -o d:e:hm:v:: -l builddir:,color:,colour:,debug,docconfig:,dapsroot:,envfile:,fb_styleroot:,help,main:,styleroot:,verbosity::,version -n $ME -- "$@")

# Exit when getopt returns errors
#
GETOPT_RETURN_CODE=$?
[[ 0 != $GETOPT_RETURN_CODE ]] && exit $GETOPT_RETURN_CODE

eval set -- "$ARGS"

while true ; do
    case "$1" in
         --builddir)
            [[ -d $2 ]] || exit_on_error "BUILD_DIR \"$2\" is not a valid directory"
            [[ -w $2 ]] || exit_on_error "BUILD_DIR \"$2\" is not writeable"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "BUILD_DIR_CMDL"
            BUILD_DIR="$BUILD_DIR_CMDL"
            shift 2
            ;;
        --color|--colour)
            if [[ 1 != $2 && 0 != $2 ]]; then
                exit_on_error "Wrong value ($2) for COLOR. Must be \"0\" or \"1\""
            fi
            COLOR_CMDL=$2
            export COLOR="$COLOR_CMDL"
            shift 2
            ;;      
        -d|--docconfig|-e|--envfile)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "DOCCONF_CMDL"
            DOCCONF="$DOCCONF_CMDL"
            shift 2
            ;;
        --dapsroot)
            [[ -d $2 ]] || exit_on_error "DAPSROOT \"$2\" is not a valid directory"
            # make path absolute and strip trailing slash
            sanitize_path "$2" "DAPSROOT_CMDL"
            DAPSROOT="$DAPSROOT_CMDL"
            DEVEL=1
            shift 2
            ;;
        --debug)
            # debug also implies VERBOSITY=2
            DEBUG=1
            VERBOSITY_CMDL=2
            VERBOSITY=$VERBOSITY_CMDL
            shift
            ;;
        --fb_styleroot)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "FALLBACK_STYLEROOT_CMDL"
            FALLBACK_STYLEROOT="$FALLBACK_STYLEROOT_CMDL"
            shift 2
            ;;
        -h|--help)
            # if it's just "-h/--help", then print the global daps help
            # if "-h/--help" is followed by a subcommand, then set a marker
            # to call the subcommand's help
            shift;
            if [[ "" = $2 ]]; then
                daps_help
                exit 0;
            else
                CALL_SCMDHELP=1
            fi
            ;;
        --main)
            # make path absolute and strip trailing slash
	    sanitize_path "$2" "MAIN_CMDL"
	    MAIN="$MAIN_CMDL"
	    shift 2
            ;;
        --styleroot)
            # make path absolute and strip trailing slash
            sanitize_path "$2" "STYLEROOT_CMDL"
            STYLEROOT="$STYLEROOT_CMDL"
            shift 2
            ;;
	-v|--verbosity)
            # $VERBOSITY will be parsed in the makefiles
            # VERBOSITY=0: print only final results message (default)
            # VERBOSITY=1: results of each target that is called
            # VERBOSITY=2: detailed output of each target
            #
            if [[ 1 = $DEBUG ]]; then
                VERBOSITY_CMDL=2
            else
                if [[ 0 = $2 ]]; then
                    VERBOSITY_CMDL=0
                 elif [[ 1 = $2 || "" = $2 ]]; then
                    VERBOSITY_CMDL=1
                else
                    VERBOSITY_CMDL=2
                fi
            fi
            VERBOSITY="$VERBOSITY_CMDL"
	    shift 2
	    ;;
        --version)
            echo "$ME $VERSION"
            exit 0
            ;;
        --) shift ; break ;;
        *) exit_on_error "Internal error!" ;;
    esac
    
done

# You can only specify DOCCONF or MAIN, not both
#
if [[ -n $DOCCONF_CMDL && -n $MAIN_CMDL ]]; then
    exit_on_error "The options -d/--docconfig and --main exclude each other."
fi

# Check FALLBACK_STYLEROOT and STYLEROOT
#
if [[ -n $FALLBACK_STYLEROOT && -z $STYLEROOT ]]; then
    echo "--styleroot is not specified, ignoring --fb_styleroot"
fi 


unset POSIXLY_CORRECT # we want the regular getopts behaviour on the second run

#-----------------------------------
# Store the subcommand and it's args

# extract the subcommand from $@ if $ME has been called with no arguments
# or with "help" as the only argument, run global help. If it was called with
# SUBCOMMAND help or help SUBCOMMAND, rewrite the command so the subcommand help
# is displayed.

if [[ -z $1 ]] || [[ help = $1 && -z $2 ]]; then
    # Call: "$ME" or "$ME help"
    #
    daps_help
    exit 0
elif [[ help = $2 ]]; then
    # Call: "$ME foo help ..."
    # Rewrite to "$ME foo -h"
    #
    SUBCMD=$1
    declare -a SCMD_ARGS=( "-h" )
elif [[ help = $1 && -n $2 ]]; then
    # Call: "$ME help foo"
    # Rewrite to "$ME foo -h"
    #
    SUBCMD=$2
    declare -a SCMD_ARGS=( "-h" )
elif [[ 1 = $CALL_SCMDHELP ]]; then
    SUBCMD=$1
    declare -a SCMD_ARGS=( "-h" )
else
    # No help
    SUBCMD=$1
    shift
    declare -a SCMD_ARGS=( "$@" )
fi

# Now that we have the subcommand
# - check whether it is valis
# - get the function from lib/daps_functions that needs to be called for $SUBCMD
# - get it's help text
FUNCTION=$(arrayGet "SUBCOMMANDS" "$SUBCMD")
if [[ 1 = $? ]]; then
    exit_on_error "Error: Unknown subcommand \"$SUBCMD\"\nType '$ME help' to get a list of global parameters and subcommands"
fi
HELP_SUBCMD=$(arrayGet "HELP_SUBCOMMAND" "$SUBCMD")

# Now check, whether subcommand help has been requested by -h or --help
# anywhere in the argument string or if SCMD_ARGS contains bad strings
#
case "${SCMD_ARGS[@]}" in
    "-h"|"-h "*|*" -h "*|*" -h"|"--help"|"--help "*|*" --help "*|*" --help")
        declare -a SCMD_ARGS=( "-h" )
        ;;
    *DOCCONF*|*DAPSROOT*|*DOC_DIR*|*MAIN*)
        if [[ showvariable != $SUBCMD ]]; then
            exit_on_error "Please specify DOC_DIR, DOCCONF, MAIN, or DAPSROOT via command line options"
        fi
esac


# ----------------------------------------------------------------------------
# Setting up the environment for the complete mechanics
#
# The environment is set up using the following hierachy
# (1 == always wins)
#
# 1. Command line 
#    - either as a real option
#    - or as variable declaration (FOO=bar) --> debugging and developing
# 2. DC-file
# 3. $USER_CONFIG (user config file)
# 4. @sysconfig@/daps/config or $DAPSROOT/etc/config
#
# In order to make developing easier, there is a hidden feature to set
# DAPSROOT, allowing to have multiple daps versions installed into
# different directories. You can switch between them by setting DAPSROOT
# accordingly. Either by command line switch --dtdroot or in  your user
# config file (DAPSROOT="<path>") 
#
# Since commandline values take precedence we need to recover them every
# time we source a file
#

# source the user config for the first time to get DAPSROOT
#
if [[ -f $USER_CONFIG && -z $DAPSROOT_CMDL ]]; then
    source "$USER_CONFIG"
    # make DAPSROOT path absolute and remove trailing /
    [[ -n $DAPSROOT ]] && sanitize_path "$DAPSROOT" "DAPSROOT" \
        $(readlink -en $(dirname $USER_CONFIG))
    recover_cmdl_values
fi

# IF we have a custom DAPSROOT, $DAPSROOT is set by now - if not, use the default
if [[ -n $DAPSROOT ]]; then
    # custom DAPSROOT was set
    if [[ ! -d "$DAPSROOT" ]]; then
        exit_on_error exit_on_error "DAPSROOT \"$2\" is not a valid directory"
    else
        # valid directory
        #  strip trailing slash
        DAPSROOT=${DAPSROOT%/}
        BIN_DIR="${DAPSROOT}/bin"
        export PATH=$BIN_DIR:$PATH
        LIB_DIR="${DAPSROOT}/lib"
        PYTHON_DIR="${DAPSROOT}/python"
        LIBEXEC_DIR="${DAPSROOT}/libexec"
        CONFIG="${DAPSROOT}/etc/config"
        XML_CATALOG_FILES="$XML_CATALOG_FILES $DAPSROOT/etc/catalog.xml"
    fi
else
    # default DAPSROOT
    # no need to set BIN_DIR here, since it should be in the default path
    #
    # if DAPSROOT_DEFAULT contains @...@ we are operating from an SVN
    # checkout and no  --dapsroot was set
    #
    [[ $DAPSROOT_DEFAULT =~ @[a-zA-Z]*@ ]] && exit_on_error "You need to specify a DAPSROOT when using an SVN checkout"
    DAPSROOT="$DAPSROOT_DEFAULT"
    LIB_DIR="$DEFAULT_LIB_DIR"
    LIBEXEC_DIR="$DEFAULT_LIBEXEC_DIR"
    CONFIG="$DEFAULT_CONFIG"
fi

# ---------------------------------------------
# Source functions and system config
#
# Now that everything is in place, source the functions, the system config
# and the user config (again)
source "$LIB_DIR/daps_functions"
source "$CONFIG"

# ---------------------------------------------
# Source user config
#
if [[ -f $USER_CONFIG ]]; then
    source "$USER_CONFIG"
    # make paths from PATHLIST absolute and remove trailing /
#    MY_BASEDIR=$(readlink -en $(dirname $USER_CONFIG))
#    check_pathlist "$MY_BASEDIR"
    # make DAPSROOT path absolute and remove trailing /
    [[ -n $DAPSROOT ]] && sanitize_path "$DAPSROOT" "DAPSROOT" \
        $(readlink -en $(dirname $USER_CONFIG))
fi
recover_cmdl_values

#----------------------------------
# Run early commands that do not need to have an environment fully set up

#
# run help if requested
#
if [[ "${SCMD_ARGS[@]}" = "-h" ]]; then
    eval "$FUNCTION $SUBCMD ${SCMD_ARGS[@]}"
fi

# Sample call for early commands
#
#case "$SUBCMD" in
#    foo)
#      eval "$FUNCTION $SUBCMD ${SCMD_ARGS[@]}"
#      exit
#      ;;
#esac

#-------------------------------------
# Source DOCCONF and set up MAIN, DOC_DIR
#
# The black magic part of daps ... ;-)
#
# Three possibilities:
# 1. MAIN was set on the command line or via user config
# 2. DOCCONF was set on the command line
# 3. MAIN and DOCCONF were _not_ set
#
# Use MAIN_CMDL and DOCCONF_CMDL in the following in order to avoid that
# these get overwritten by chance with values from the DOCCONF files
# (DOCCONF should never be set in a DC file and MAIN_CMDL should always
# overwrite a MAIN setting from DOCCONF)
# The real values will be set when calling recover_cmdl_values

# set DOCCONF_CMDL if DC-file was sourced
[[ -n $DOCCONF && -z $DOCCONF_CMDL ]] && DOCCONF_CMDL=$DOCCONF 

if [[ -z $DOCCONF_CMDL && -z $MAIN_CMDL ]]; then
# DOCCONF and MAIN were not set on the command line, check other possibilities
    if [[ -n $DOCCONF_NAME ]]; then
    # check if DOCCONF was sourced
    # takes precedence over a default set in config
        if [[ -e "$DOCCONF_NAME" ]]; then
            sanitize_path "$DOCCONF_NAME" "DOCCONF_CMDL"
            DOC_DIR=$(dirname "$DOCCONF_CMDL")
            if [[ 1 -le $VERBOSITY ]]; then
                echo "Using previously sourced DOCCONF $DOCCONF_CMDL"
            fi
        else
            exit_on_error "Cannot find previously sourced DOCCONF \"$DOCCONF_NAME\".\nWhen sourcing the doc config, you either need to run $ME from the directory\nwhere you sourced the config, or you need to provide an absolute path when\nsourcing the doc config."
        fi
    elif [[ -n $DOCCONF_DEFAULT ]]; then
    # check if a default value was specified in the user/system config file
        if [[ -e $DOCCONF_DEFAULT ]]; then
            sanitize_path "$DOCCONF_DEFAULT" "DOCCONF_CMDL"
            DOC_DIR=$(dirname "$DOCCONF_CMDL")
            if [[ 1 -le $VERBOSITY ]]; then
                echo "Using DOCCONF $DOCCONF_DEFAULT from config files"
            fi
        else
            exit_on_error "DOCCONF_DEFAULT \"$DOCCONF_DEFAULT\" not found in current directory.\nCheck your config file at $USER_CONFIG."
        fi
    else
    # try to automatically set DOCCONF
        autoset_docconf
    fi
elif [[ -n $MAIN_CMDL ]]; then
    # MAIN was set on the command line or in the user config
    set_mainfile "$MAIN_CMDL"
elif [[ -n $DOCCONF_CMDL ]]; then
    # check if DOCCONF is a regular file
    if [[ -e $DOCCONF_CMDL ]]; then
        sanitize_path "$DOCCONF_CMDL" "DOCCONF_CMDL"
        DOC_DIR=$(dirname "$DOCCONF_CMDL")
    else
        exit_on_error "The file \"$DOCCONF\" you specified with --docconf is not a valid file"
    fi
fi

#
# Checking MAIN_CMDL, DOCCONF_CMDL, DOC_DIR and DAPSROOT
#

[[ -z "$DOCCONF_CMDL" && -z "$MAIN_CMDL" ]] && exit_on_error "Fatal: Neither \$DOCCONF nor $MAIN are set. This should not have happened"
[[ -z "$DOC_DIR" ]] && exit_on_error "Fatal: \$DOC_DIR is not set. This should not have happened. Please report a bug."
[[ -z "$DAPSROOT" ]] && exit_on_error "Fatal: \$DAPSROOT is not set. This should not have happened. Please report a bug."

# FINALLY! Source the DOCCONF file, recover the command line values

[[ -n $DOCCONF_CMDL ]] && source $DOCCONF_CMDL

# FOP/XEP CONFIG and WRAPPER
# when using an SVN checkout, /etc and @pkgdatadir have not been
# replaced
#
# ${string/#substring/replacement}
# If $substring matches front end of $string, substitute
# $replacement for $substring.

FOP_CONFIG_FILE=${FOP_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}
FOP_WRAPPER=${FOP_WRAPPER/#@pkgdatadir\@/${DAPSROOT}}

XEP_CONFIG_FILE=${XEP_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}
XEP_WRAPPER=${XEP_WRAPPER/#@pkgdatadir\@/${DAPSROOT}}

# make all paths absolute, remove trailing / and check
MY_BASEDIR=$(readlink -en $(dirname $DOCCONF_CMDL))
check_pathlist "$MY_BASEDIR"
recover_cmdl_values

# If MAIN was not specified on the command line, set MAIN to an absolute
# path
if [[ -z "$MAIN_CMDL" ]]; then
    set_mainfile "$MAIN"
    MAIN="$MAIN_CMDL"
fi


#----------
# Values that need to be exported and are not set in the config
#

# book name
if [[ -n $PDFNAME ]]; then
    export BOOK="$PDFNAME"
else
    if [[ -n $DOCCONF ]]; then
        DC_FILE=$(basename $DOCCONF)
        export BOOK="${DC_FILE#${CONF_PREFIX}*}"
    elif [[ -n "$MAIN_CMDL" ]]; then
        # --main was specified, BOOK is set to basenme of MAIN
        export BOOK=$(basename $MAIN .xml)
    fi
fi

# XML_CATALOG_FILES
if [[ -n $XML_CATALOG_FILES ]]; then
    export XML_CATALOG_FILES
fi

# ----------------------------------------------------------------------------
# Set paths
#
# set all basic paths that have not been set by now

#----------------------------------
# default BUILD_DIR if not specified elsewhere
[[ -z $BUILD_DIR ]] && BUILD_DIR=${DOC_DIR}/build

#----------------------------------
# DocBook Stylesheet locations
#
# get DocBook version first ...
DOCBOOK_VERSION=$(xsltproc \
    ${DAPSROOT}/daps-xslt/common/get-docbook-version.xsl $MAIN) || exit_on_error "Could not get DocBook version. Seems $MAIN is not well-formed"

#    || { DOCBOOK_VERSION=4; \
#      "Could not get DocBook version, assuming DocBook 4"; } 

# ... now resolve the style URI via catalogs
if [[ 5 = $DOCBOOK_VERSION ]]; then
    DOCBOOK_STYLES=$(xmlcatalog $XML_MAIN_CATALOG \
        $DOCBOOK5_STYLE_URI 2>/dev/null) || \
        exit_on_error "Could not determine the DocBook stylesheet location by\nresolving $DOCBOOK5_STYLE_URI\n via xmlcatalog"
    # also get the RNG scheme location
    DOCBOOK5_RNG=$(xmlcatalog $XML_MAIN_CATALOG \
        $DOCBOOK5_RNG_URI 2>/dev/null) || \
        exit_on_error "Could not determine the DocBook 5 schema location by\nresolving $DOCBOOK5_RNG_URI\n via xmlcatalog"
elif [[ 4 = $DOCBOOK_VERSION ]]; then
    DOCBOOK_STYLES=$(xmlcatalog $XML_MAIN_CATALOG \
        $DOCBOOK4_STYLE_URI 2>/dev/null) || \
        exit_on_error "Could not determine the DocBook stylesheet location by\nresolving $DOCBOOK4_STYLE_URI\n via xmlcatalog"
else
    exit_on_error "Fatal: Could not determine the DocBook version from $MAIN" 
fi

# remove the file:// string from the styles
# use ##*file:// rather than #file:// because sometimes xmlcatalog also outputs
# warnings to stdout which we would like to ignore. Fortunately the file:// url
# is always the last string
#
DOCBOOK_STYLES=${DOCBOOK_STYLES##*file://}
DOCBOOK_STYLES=${DOCBOOK_STYLES%/}
DOCBOOK5_RNG=${DOCBOOK5_RNG##*file://}

# ...and export
export DOCBOOK_STYLES DOCBOOK5_RNG DOCBOOK_VERSION

#----------------------------------
# Result directory / LOG directory
#
R_DIR="${BUILD_DIR}/${BOOK}/"
LOG_DIR="${R_DIR}/log"


#-------------------------------------------------------------------
# Now export all variables set by the config file
export "${VARLIST[@]}"

#-------------------------------------------------------------------
# Finally, run the Subcommands
#

# By default we want to write a logfile, can be overwritten by
# subcommand function
#
WRITE_LOG=1

eval "$FUNCTION $SUBCMD ${SCMD_ARGS[@]}"


