#!/bin/bash
#
# Copyright (C) 2011 fs@suse.de, openSUSE.org
# Authors: fs@suse.de
#
# daps = DocBook Authoring and Publishing Suite


VERSION=0.9.1


# ----------------------------------------------------------------------------
# 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
# Whenever a new variable is introduced, it needs to be added here!!
#
declare -a VARLIST
# VENDOR is for unsetting only, since it is a default tcsh variable
VARLIST=(
    BASE_DIR
    BUILD_DIR
    CB_OPTIONS
    CHECKBOT
    COLOR
    COMMENTS
    COMMENT_STR
    CONF_PREFIX
    CONVERT_OPTS
    DEBUG
    DEF_FILE
    DIA_OPTIONS
    DISTVER
    DRAFT
    DRAFT_STR
    FOPOPTIONS
    FOPTYPE
    HTMLROOT
    INK_OPTIONS
    LAYOUT
    LOG_DIR
    MAIN
    NOPDF
    PDFNAME
    PRODUCTNAME
    PRODUCTNAMEREG
    PROFARCH
    PROFCONDITION
    PROFOS
    PROFVENDOR
    REMARKS
    REMARK_STR
    ROOTID
    STATIC_HTML
    STYLEFO
    STYLEH
    STYLENOV
    TITLE
    USEMETA
    VERBOSITY
    XSLTPARAM
)

# VARLIST contains all variables that can be set via config or command line.
# 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=(
    BASE_DIR_CMDL
    BUILD_DIR_CMDL
    BIN_DIR
    BOOK
    COLOR_CMDL
    CONFIG
    DTDROOT
    DTDROOT_CMDL
    ENVFILE
    ENVFILE_CMDL
    FOP_CONFIG_FILE
    LIB_DIR
    SILENT
    VENDOR
    VERBOSITY_CMDL
)

# unset all for a fresh start
unset "${VARLIST[@]}"
unset "${UNSETLIST[@]}"

#
# Associative array with
#  Key   = subcommand
#  Value = function call (from lib/daps_functions)
# 
# 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
    [bigfile-reduced]=build_generic
    [bigfile]=build_generic
    [check]=call_make_nolog
    [checklink]=checklink
    [chklink]=checklink
    [clean-all]=no_opts
    [clean-images]=no_opts
    [clean-results]=no_opts
    [clean]=no_opts
    [color-pdf-name]=show_names
    [color-pdf]=build_pdfs
    [db2novdoc]=build_generic
    [desktop-files-dir-name]=show_names
    [desktop-files]=build_generic
    [dist-all]=profile_first
    [dist-book]=build_generic
    [dist-desktop-files]=build_generic
    [dist-document-files-html]=build_generic
    [dist-document-files-pdf]=build_generic
    [dist-graphics-png]=build_generic
    [dist-graphics]=build_generic
    [dist-html-name]=show_names
    [dist-html-single]=build_generic
    [dist-html]=build_generic
    [dist-htmlsingle]=build_generic
    [dist-jsp]=build_generic
    [dist-xml]=build_generic
    [dist]=build_generic
    [document-files-dir-name]=show_names
    [document-files-html]=build_generic
    [document-files-pdf]=build_generic
    [epub-name]=show_names
    [epub]=build_epub
    [force]=build_pdfs
    [getimages]=getimages
    [html-dir-name]=show_names
    [html-single-name]=show_names
    [html-single]=build_html_jsp
    [html]=build_html_jsp
    [htmlsingle-name]=show_names
    [htmlsingle]=build_html_jsp
    [init]=init_wd
    [jana]=checklink
    [jsp-dir-name]=show_names
    [jsp]=build_html_jsp
    [locdrop]=build_locdrop
    [missinggraphics]=filelists
    [nothing]=no_opts
    [offspring]=no_opts
    [online-docs]=build_generic
    [online-localized]=build_generic
    [optipng]=build_generic
    [package-html]=packaging
    [package-jsp]=packaging
    [package-pdf]=packaging
    [package-src-name]=show_names
    [package-src]=packaging
    [package]=packaging
    [pdf-color-name]=show_names
    [pdf-color]=build_pdfs
    [pdf-name]=show_names
    [pdf]=build_pdfs
    [penguin]=no_opts
    [prof]=build_generic
    [profile]=build_generic
    [profiledir]=comments_remarks
    [projectfiles]=filelists
    [projectgraphics]=filelists
    [provide-color-images]=build_generic
    [provide-epub-images]=build_generic
    [provide-images]=build_generic
    [real-clean]=no_opts
    [remainingfiles]=filelists
    [remaininggraphics]=filelists
    [showenv]=show_env
    [showvariable]=profile_first
    [text]=build_generic
    [txt-name]=show_names
    [txt]=build_generic
    [validate]=comments_remarks
    [wiki-name]=show_names
    [wiki]=build_generic
    [xmlgraphics-bw]=filelists
    [xmlgraphics]=filelists
)



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

function daps_help () {
    echo "
Usage:
  $ME [--global-options] <subcommand> [--command-options] [arguments]

Global Options:
  -b BASE_DIR,
  --basedir=BASE_DIR        Project directory. Must contain the XML sources in
                            BASE_DIR/xml. If not specified, the current
                            directory will be used
                            Default: Parent directory of $ENVFILE
  --builddir=BUILD_DIR      Directory where every output $ME generates will end
                            up
                            Default: ${BASE_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
  -e ENVFILE,
  --envfile=ENVFILE         Specify which ENV file to use. Mandatory unless
                            there is only a single ENV file in BASE_DIR. In
                            that case the ENV file will automatically be used.
                            Specify only the filename, not an absolute path.
  --help, -h                Help
  --main                    Path to the main file defining your document.
                            Specify only the filename, not an absolute path
  --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
    dist                      b/w pdf with cropmarks for each chapter
    epub                      ePUB book
    force                     b/w pdf with cropmarks. Force updating the
                              profiled sources and the .fo file
    html                      HTML book
    html-single, htmlsingle   Single file HTML book
    jsp                       JSP book
    man                       man pages
    pdf                       b/w pdf with cropmarks
    txt, text                 ASCII book
    wiki                      Single file MediaWiki book


  Create Distributable Archives:
    dist-all                  Shortcut for running the subcommands 'validate'
                              'chklink' '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 need to translate a set

  File lists:
    projectfiles              Print XML source files 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
    xmlgraphics               Print (generated) color graphics really used to
                              generate the books
    xmlgraphics-bw            Print (generated) b/w 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.
                              generated from the ENV file used
    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 (novell.com):
    online-docs               Provide a profiled XML bigfile and a graphics
                              tarball (PNG only)
    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

  Other Commands:
    chklink                   Linkchecker for links from <ulink> tags
    db2novdoc                 Convert DocBook XML sources to NovDoc
    getimages                 List or display images from a profiled DocBook
                              XML file
    init                      Create a working directory to get started with
                              daps/DocBook. Generates a MAIN xml file and a
                              fitting ENVfile
    optipng                   Optimize (size) source PNGs
    profile, prof             Profile XML sources
    validate                  Validate profiled sources. Automatically profiles
                              the XML sources if needed

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

  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.
"
}

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

# ---------
# Recover command-line values
#
function recover_cmdl_values () {
    test -n "$BASE_DIR_CMDL"  && BASE_DIR="$BASE_DIR_CMDL"
    test -n "$BUILD_DIR_CMDL" && BUILD_DIR="$BUILD_DIR_CMDL"
    test -n "$COLOR_CMDL"     && COLOR="$COLOR_CMDL"
    test -n "$DTDROOT_CMDL"   && DTDROOT="$DTDROOT_CMDL"
    test -n "$ENVFILE_CMDL"   && ENVFILE="$ENVFILE_CMDL"
    test -n "$MAIN_CMDL"      && MAIN="$MAIN_CMDL"
    test -n "$VERBOSITY_CMDL" && VERBOSITY="$VERBOSITY_CMDL"
}

# ---------
# Try to automatically set $BASE_DIR
#
function get_basedir () {
    if [[ -d $PWD/xml ]]; then
        # current directory is the BASE_DIR
        BASE_DIR="$PWD"
        return 0
    elif [[ -h $ENVFILE ]]; then
        # ENVFILE is a link
        # assume the real directory of $ENVFILE is BASE_DIR
        BASE_DIR=$(dirname $(readlink $ENVFILE))
        return 0
    elif [[ -f $MAIN ]]; then
        BASE_DIR=$(dirname $MAIN)
        BASE_DIR=${BASE_DIR%/xml*} #remove xml directory
    else
        return 42; # ;-)
    fi
}

# ---------
# Try to automatically set $ENVFILE
#
function get_envfile () {
    local ENV_COUNT=$(find -L $PWD -maxdepth 1 -name "${CONF_PREFIX}*" -type f | wc -l)
    if [[ 1 = $ENV_COUNT ]]; then
        # a single ENVFILE was found
        ENVFILE=$(find -L $PWD -maxdepth 1 -name "${CONF_PREFIX}*" -type f)
	ENVFILE=$(basename $ENVFILE)
        return 0;
    else
        return 42;
    fi
}

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

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

# The default DTDROOT 
DEFAULT_DTDROOT="/usr/share/daps"

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

# default libdir
DEFAULT_LIB_DIR="${DEFAULT_DTDROOT}/lib"

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


# ----------------------------------------------------------------------------
# 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 (and only if) $BASE_DIR, $BUILD_DIR, $ENVFILE, and $DTDROOT are set here,
# we do not want to overwrite them by any other file we source
# (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 b:e:hv:: -l basedir:,builddir:,color:,colour:,debug,dtdroot:,envfile:,help,main:,verbosity::,version -n $ME -- "$@")
eval set -- "$ARGS"

while true ; do
    case "$1" in
        -b|--basedir)
            test -d "$2" || exit_on_error "BASE_DIR $2 is not a valid directory"
            BASE_DIR_CMDL="$2"
            BASE_DIR="$BASE_DIR_CMDL"
            shift 2
            ;;
         --builddir)
            test -d "$2" || exit_on_error "BUILD_DIR $2 is not a valid directory"
            test -w "$2" || exit_on_error "BUILD_DIR $2 is not writeable"
            BUILD_DIR_CMDL="$2"
            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
            ;;      
        --debug)
            # debug also implies VERBOSITY=2
            DEBUG=1
            VERBOSITY_CMDL=2
            VERBOSITY=$VERBOSITY_CMDL
	    shift
	    ;;
        --dtdroot)
	    test -d $2 || exit_on_error "$2 is not a valid DTDROOT"
	    DTDROOT_CMDL="$2"
	    DTDROOT="$DTDROOT_CMDL"
	    shift 2
            ;;
	-e|--envfile)
	    ENVFILE_CMDL="$2"
            ENVFILE="$ENVFILE_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)
	    MAIN_CMDL="$2"
	    MAIN="$MAIN_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

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 valid

if [[ -z ${SUBCOMMANDS[$SUBCMD]} ]]; then
    ccecho "error" "Error: Unknown subcommand \"$SUBCMD\"" >&2
    ccecho "normal" "Type '$ME help' to get a list of global parameters and subcommands" >&2
    exit 1;
fi

# 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" )
        ;;
    *ENVFILE*|*DTDROOT*|*BASE_DIR*|*MAIN*)
        exit_on_error "Please specify BASE_DIR, ENVFILE, or DTDROOT via command line options" 
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)
#
# 2. ENV-file
# 3. $USER_CONFIG (user config file)
# 4. /etc/daps/config or $DTDROOT/etc/config
#
#
# In order to make developing easier, there is a hidden feature to set
# DTDROOT, allowing to have multiple daps versions installed into
# different directories. You can switch between them by setting DTDROOT
# accordingly (without a trailing slash)
#
# IMPORTANT:
# DTDROOT MUST be set by either $ME --dtdroot $SCMD on the commandline
# or in $USER_CONFIG
#
# If DTDROOT was not already set on the commandline (in this case
# DTDROOT_CMDL would be set), source the USER config to find out
# if DTDROOT was set there.
#
# commandline values for $BASE_DIR, $BUILD_DIR, $ENVFILE, and $DTDROOT take
# precedence we need to recover them _every_ time we source a file
#
if [[ -f $USER_CONFIG && -z $DTDROOT_CMDL ]]; then
    source "$USER_CONFIG"
    recover_cmdl_values
fi

# IF we have a custom DTDROOT, $DTDROOT is set by now - if not, use the default
if [[ -n $DTDROOT ]]; then
    # custom DTDROOT was set
    if [[ ! -d "$DTDROOT" ]]; then
        exit_on_error "dtdroot $DTDROOT is no valid directory"
    else
        # valid directory
        BIN_DIR="${DTDROOT}/bin"
        export PATH=$BIN_DIR:$PATH
        LIB_DIR="${DTDROOT}/lib"
        CONFIG="${DTDROOT}/etc/config"
        XML_CATALOG_FILES="$DTDROOT/etc/catalog.xml"
    fi
else
    # default DTDROOT
    #
    # no need to set BIN_DIR here, since it is /usr/bin
    DTDROOT="$DEFAULT_DTDROOT"
    LIB_DIR="$DEFAULT_LIB_DIR"
    CONFIG="$DEFAULT_CONFIG"
fi

# Now that everything is in place, source the functions, the system config
# and the user config (again)

source "$LIB_DIR/daps_functions"
source "$CONFIG"
if [[ -f $USER_CONFIG ]]; then
    source "$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 "${SUBCOMMANDS[$SUBCMD]} $SUBCMD ${SCMD_ARGS[@]}"
fi

# Initialize a working directory
#
case "$SUBCMD" in
    init)
      "${SUBCOMMANDS[$SUBCMD]}" "${SCMD_ARGS[@]}"
      exit
      ;;
esac

#-------------------------------------
# Set up BASE_DIR and ENVFILE

# There are three possibilities to set an ENV file:
# 1. Command line:
#    $ENVFILE is set - takes precedence over 2. and 3.
# 2. ENV files has been sourced:
#    $DAPS_ENV_NAME is set - takes precedence over 3.
# 3. Default ENV has been set in ~/.daps/config
#    $DAPS_ENV_DEFAULT is set
#
# if ENVFILE or MAIN are already set, we skip the while loop
# if 2. and 3. fail, we try to set ENVFILE automatically
#

if [[ -z $ENVFILE && -z $MAIN ]]; then 
    # first check for $DAPS_ENV_NAME
    if [[ -n $DAPS_ENV_NAME ]]; then
        ENVFILE="$DAPS_ENV_NAME"
    # second check for $DAPS_ENV_DEFAULT
    elif [[ -n $DAPS_ENV_DEFAULT ]]; then
        ENVFILE="$DAPS_ENV_DEFAULT"
    # last, try to get the ENVfile automatically
    get_envfile    
    elif [[ 0 != $? ]]; then
        # seting ENVfile failed
        exit_on_error "Please specify an ENV or a MAIN file at the command line"
    fi
fi

# If we arrive here, either ENVFILE, MAIN or both are set (or we have exited)
# So we try to get a BASE_DIR if it does not exist
#
if [[ -z $BASE_DIR ]]; then
    get_basedir
    if [[ 0 != $? ]]; then
        if [[ -n $ENVFILE ]]; then
            exit_on_error "Cannot find a valid BASEDIR for ENVFILE \"$ENVFILE\""
        elif [[ -n $MAIN ]]; then
            exit_on_error "Cannot find a valid BASEDIR for MAIN file \"$MAIN\""
        else
            exit_on_error "Please specify a BASE_DIR at the command line"
        fi
    fi
elif [[ ! -d ${BASE_DIR}/xml ]]; then
    exit_on_error "Could not find an xml/ subdirectory in BASE_DIR $BASE_DIR"
fi

# If we arrive here, BASE_DIR is set and valid (or we have exited)
# Now check, whether ${BASE_DIR}/$ENVFILE and ${BASE_DIR}/$MAIN are valid, too
#
if [[ -n $ENVFILE ]]; then
    if [[ ! -f ${BASE_DIR}/$ENVFILE ]]; then
        exit_on_error "\nENVFILE: \"$ENVFILE\" in BASEDIR: $BASE_DIR\ncould not be found. Check the respective commandline options or the config files"
    else
        # exit on old ENV files
        egrep "^\s*[^#]*(\.|source)\s+\.env-profile" ${BASE_DIR}/$ENVFILE >/dev/null && exit_on_error "Looks like you are going to use an old susedoc ENVfile."
        if [[ 0 != $VERBOSITY ]]; then
            ccecho "info" "Using ENVFILE $ENVFILE in BASEDIR $BASE_DIR"
        fi
    fi
elif [[ -n $MAIN ]]; then
    if [[ ! -f ${BASE_DIR}/xml/$MAIN ]]; then
        exit_on_error "\nMAIN file: \"$MAIN\" in BASEDIR: $BASE_DIR/xml\ncould not be found. Check the respective commandline options or the config files"
    else
        if [[ 0 != $VERBOSITY ]]; then
            ccecho "info" "Using MAIN file $MAIN in BASEDIR $BASE_DIR"
        fi
    fi
fi

#
# FINALLY! Source the ENV-file, recover the command line values and we
# are done setting the environment

if [[ -n $ENVFILE ]]; then
    source ${BASE_DIR}/$ENVFILE
    recover_cmdl_values
fi

#----------
# Check some values
#

# COLOR must be set to 1|0
#
# if we are not in a terminal but rather in a pipe, script, etc.
# disable color output otherwise use the value specified on the
# command line or in the config
#
# checking for a Terminal is done by "test -t 1"

if [[  -t 1 ]]; then
    case $COLOR in
        "1" | "yes")
            COLOR=1
            ;;
        "0" | "no" | "")
            COLOR=0
            ;;
        *)
            exit_on_error "Wrong value for COLOR. Must be \"yes\" or \"no\""
            ;;
        esac
else
    # No terminal
    COLOR=0
fi

# MAIN
if [[ ! -f ${BASE_DIR}/xml/$MAIN ]]; then
    exit_on_error "MAIN ${BASE_DIR}/xml/$MAIN does not exist"
fi

#----------
# Export environment-depending variables
#

# book name
if [[ -n $PDFNAME ]]; then
    export BOOK="$PDFNAME"
else
    export BOOK="${ENVFILE#*${CONF_PREFIX}}"
fi

# DTDROOT
export DTDROOT
export DEFAULT_DTDROOT

# ENVFILE
export ENVFILE

# LIB_DIR
export LIB_DIR

# FOP
export FOP="${LIB_DIR}/daps-$FOPTYPE"

# PATH
if [[ -n $BIN_DIR ]]; then
    export PATH=$BIN_DIR:$PATH
fi

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

# R_DIR / LOG_DIR
#
if [[ -n $BUILD_DIR ]]; then
    R_DIR="${BUILD_DIR}/${BOOK}/"
    LOG_DIR="${R_DIR}/log"
else
    R_DIR="${BASE_DIR}/build/${BOOK}"
    LOG_DIR="${R_DIR}/log"
fi

#----------
# 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 "${SUBCOMMANDS[$SUBCMD]} $SUBCMD ${SCMD_ARGS[@]}"

#run_subcmd;

