#!/bin/bash
#
# Copyright (C) 2012-2018 SUSE Linux GmbH
#
# Author:
# Frank Sundermeyer <fsundermeyer at opensuse dot org>
#
# Used as a wrapper script, so it's not necessary to memorize
# where the config file stays

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

# set to default if empty
#XMLFORMAT_CONFIG_FILE="@sysconfdir@/daps/docbook-xmlformat.conf"
#

XMLFORMAT_CONFIG_FILE=${XMLFORMAT_CONFIG_FILE:-"@sysconfdir@/daps/docbook-xmlformat.conf"}


# when using a Git checkout, @sysconfdir@ has not been
# replaced
#
# ${string/#substring/replacement}
# If $substring matches front end of $string, substitute
# $replacement for $substring.



if [[ "$XMLFORMAT_CONFIG_FILE" == "@sysconfdir@"* && -z $DAPSROOT ]]; then
    _XMLF_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    DAPSROOT=${_XMLF_DIR%/bin}
fi

XMLFORMAT_CONFIG_FILE=${XMLFORMAT_CONFIG_FILE/#@sysconfdir\@\/daps/${DAPSROOT}/etc}

# Also show the config file in verbose mode
#
if [[ "${@#-v}" = "$@" || "${@#--verbose}" = "$@" ]]; then
    # use STDERR, since xmlformat prints all messages to STDERR
    >&2 echo "Using config file '$XMLFORMAT_CONFIG_FILE'"
fi

[[ -e $XMLFORMAT_CONFIG_FILE ]] || exit_on_error "Could not find config file '$XMLFORMAT_CONFIG_FILE'\n"

# Binary filename can either be xmlformat, xmlformat.rb, or xmlformat.pl ;-((
# take the first one that exists
#
for _BINARY in xmlformat xmlformat.pl xmlformat.rb; do
    XMLFORMAT_CMD="$(which "$_BINARY" 2>/dev/null)" && break
done

[[ -z "$XMLFORMAT_CMD" ]] && exit_on_error "The xmlformat script is missing. Please install the respective package!"

$XMLFORMAT_CMD --config-file "$XMLFORMAT_CONFIG_FILE" "$@"
exit $?
