#!/bin/bash

# xtcat: wrapper for lib-xt-java, arbortext catalog classes, docbook stylesheets
# Maintainer: Mark Johnson <mrj@debian.org>

# xt/arbortext wrapper script, version 0.7, Copyright (C) 2001 Mark Johnson
# This is free software; see the GPL version 2 or later. NO warranty.

# TODO: 
#     - Detect option clashing
#     - Clean up variables, write a manpage

## ----------------------------------------------------------------------
## exit on erroneous subcommand
set -e

## ----------------------------------------------------------------------
## get script name
script=$(basename $0)

## ----------------------------------------------------------------------
## print help message
function usage_message
{
    cat >&2 <<'END'

xt-catalog wrapper script, version 0.5, Copyright (C) 2001 Mark Johnson
This is free software; see the GPL version 2 or later. NO warranty.

Usage: xtcat [options] source stylesheet result {param=value}...

DocBook Usage:
  * Using 'docbook' as the stylesheet argument will automagically use the
    docbook html chunking stylesheets. 
  * The '-k' option is equivalent to a 'docbook' stylesheet arg.

'$STYLESHEET' Env Variable:
  * If no stylesheet is specified and $STYLESHEET is set, its value will be used
    as the stylesheet argument.

'$XT_PARAMS' Env Variable:
  * You can also specify stylesheet parameters by setting an 'XT_PARAMS' 
    environment variable.


Help options
  -h                     Print this help message.
  -v                     Verbose. Print all messages.
General Options:
  -k                     Chunk into HTML using DocBook stylesheets
  -j <java_interpreter>  Specify alternate java interpreter
  -D <property=value>    System property assignment (passed to java interpreter)
 --CP <classpath_prefix> Prepend entries to CLASSPATH
  -g                     Use gij, the GNU interpreter for Java bytecode
Catalog parsing options:
  -d <NUM>              Debug, or parsing verbosity. NUM=[0-3] 
                          (same as -D xml.catalog.debug=NUM)
  -c <file1[:file2...]> Catalogs to parse before system catalogs 
                          (same as -D xml.catalog.files=YOUR_CAT_FILES:SYSTEMCATS)
  -C <file1[:file2...]> Catalogs to parse (do NOT parse system catalogs) 
                          (same as -D xml.catalog.files=YOUR_CAT_FILES_ONLY)
  -s                    Prefer document system ids to catalog SYSTEM entries
                          (same as -D xml.catalog.override=false)
  -S                    Disable all catalog parsing 

END
    exit 0;
}
## ----------------------------------------------------------------------
## print some examples

function usage_examples
{
    cat >&2 <<'END'

Examples  
     Basic:  xtcat foo.xml style.xsl > foo.html      or
             xtcat -o foo.html foo.xml style.xsl 

     DocBook Chunking Stylesheets

             xtcat -k foo.xml  -or- xtcat foo.xml docbook 

     Setting stylesheet parameters: 

              xtcat -k foo.xml html.stylesheet=style.css generate.section.toc=1 
SEE ALSO
          /usr/share/doc/lib-xt-java/xt.htm

          /usr/share/doc/arbortext-catalog/docs/README.htm
               Usage notes and API docs for the Arbortext catalog classes.

END
exit 0;
}
## ----------------------------------------------------------------------
## print simplified synopsis when no arguments
function usage_synopsis
{
    cat >&2 <<'END'

Usage:    xtcat [options] source-doc stylesheet result {param=value}...

          xtcat [options] -k source-doc        {param=value}...
          xtcat [options]  source-doc docbook  {param=value}...
 
 Note: The '-k' option or a 'docbook' stylesheet argument are both equivalent 
       to a stylesheet argument with value:
       '/usr/share/sgml/docbook/stylesheet/xsl/nwalsh/html/xtchunk.xsl'

Common Options:   -k        use docbook html stylesheets (no result needed)
                  -S        disable catalog parsing
                  -g        use gij for java interpreter

Try:
       xtcat  --help-examples   usage examples
       xtcat  --help            show complete usage info (& remaining options)
END
    exit 2;
}
## ----------------------------------------------------------------------
## print error message
function usage_error
{
    echo -e >&2 "$script: $@";
    exit 2;
}


## ---------------------------------------------------------------------
## Function that checks args for equal signs

function check_arg () { valid_arg_type="$1"

    # Determine arg_type of current $arg
    # if arg contains "=", then it's a param
    [ -z `echo $arg | grep ".*=.*"` ] && arg_type="stylesheet" || arg_type="param"

    # arg is OK, set $param or $stylesheet to $arg
    if [ "$arg_type" = "$valid_arg_type" ]; then
	eval `echo -e "${valid_arg_type}=${arg}"`
	return 0
	
    elif [ arg_type="param" ]; then
	# paran args with no "=" get error message
	echo -e  "\nYour argument '$arg' isn't of the form \"param=value\" 
and therefore might be a stylesheet. Since you've already 
specified a stylesheet you may wish to cancel this run. \n  "
	echo -ne "Abort now? [Y/n]  "
	read input;
	if ! [ "$input" = "n" -o "$input" = "N" ]; then
	    usage_error "Processing cancelled."
	    exit 2;
	fi
	return 0
    else
	# remaining case: stylesheet arg not OK
	return 1
    fi
    return 0
} 


## ----------------------------------------------------------------------
## set default values

use_catalogs=true
use_gij=false
dbchunk=false
verbose=false

stylesheet=''
params=''
user_props=''
user_cp_prefix=''

## ----------------------------------------------------------------------
## set variables
system_catalog=/etc/sgml/catalog
java=/usr/bin/java
gij=/usr/bin/gij
dbstyle_home=/usr/share/sgml/docbook/stylesheet/xsl/nwalsh

dbchunk_stylesheet=$dbstyle_home/html/xtchunk.xsl
java_rep=/usr/share/java

cat_file_list=$system_catalog
cat_debug_level="1"
cat_override_val="true"

xt_jars=$java_rep/xt.jar:$java_rep/xp.jar:$java_rep/repository
catalog_jars=$java_rep/catalog.jar:$java_rep/xt-catalog.jar

catalog_parse_class=com.arbortext.xsl.sax.Driver

## ----------------------------------------------------------------------
## get command line options & arguments

shortopts="hHvSskXgD:d:C:c:"
longopts="help,help-examples,CP:"

user_input=`getopt -a -n xtcat -l $longopts -o $shortopts -- "$@"`

eval set -- "$user_input"

while test "X$1" != "X--"; do
    case "$1" in
	-v  ) verbose=true ;;
	-d  ) cat_debug_level=$2;  shift ;; 
	-c  ) cat_file_list=$2:$system_catalog; shift ;;
	-C  ) cat_file_list=$2; shift ;;
	-s  ) cat_override_val=false ;;
	-S  ) use_catalogs=false ;; 
	-g  ) use_gij=true; java=$gij ;;
	-D  ) user_props=" $1$2 "${user_props}; shift ;; 
	-k  ) dbchunk=true; ;;
	--CP ) user_cp_prefix=" $2": ; shift ;;
	-h ) usage_synopsis ;;
	--help )  usage_message ;;
	--help-examples )  usage_examples ;;	
    esac
    shift
done
shift # get rid of the '--'

## ---------------------------------------------------------
## get source file/print synosis if no input

[ -z "$1" ] && usage_synopsis
source_doc="$1"; shift


## ----------------------------------------------------------------------
## get or set stylesheet arg

! [ "$1" = "docbook" ] || { dbchunk=true; shift; }

if $dbchunk ; then
    stylesheet=$dbchunk_stylesheet
    
else
    if [ -n "$1" ]; then
	arg=$1; 
	check_arg stylesheet 
	if [ "$?" = "0" ]; then 
	    shift;
	else
	    [ -n "$XT_STYLESHEET" ] && { stylesheet=$XT_STYLESHEET; shift; }
	fi
    fi
fi

# check: if still no stylesheet arg, print error message
[ -n "$stylesheet" ] || usage_error "Stylesheet argument is missing."

## ----------------------------------------------------------------------
# check param=val args
for arg in "$@"; do
    check_arg param && params="$params $param"
    shift
done

[ -n "$XT_PARAMS" ] && params="$XT_PARAMS $params"


## ----------------------------------------------------------------------
## Parse catalogs?
## collect properties (for a readable commandline)

if [ "$use_catalogs" = "true" ]; then

    parse_class=${catalog_parse_class}

    cat_files_prop="-Dxml.catalog.files="$cat_file_list
    cat_debug_prop="-Dxml.catalog.debug="$cat_debug_level
    cat_override_prop="-Dxml.catalog.override="$cat_override_val

    xml_catalog_props=$cat_files_prop" "$cat_debug_prop" "$cat_override_prop
else
    parse_class=com.jclark.xml.sax.CommentDriver
    xml_catalog_props=''
fi

properties=$user_props" "$xml_catalog_props

## ----------------------------------------------------------------------
## set classpath
export CLASSPATH=${user_cp_prefix}$xt_jars:$catalog_jars


## ----------------------------------------------------------------------
## Construct Commandline

if [ "$use_gij" = "true" ]; then 
    cp_flag="-I"
else
    cp_flag="-cp "
fi

cmd_line="$java ${cp_flag}${CLASSPATH} $properties $parse_class $source_doc $stylesheet $result $params $*"


## ----------------------------------------------------------------------
## Messages

if [ $verbose = true ]; then
    echo
    echo "Sourcefile             "$source_doc
    echo "Stylesheet:            "$stylesheet
    [ -n "$params" ] && echo "Params:                "$params
    if [ "$dbchunk" = "false" ]; then 
	echo "Result                 "$result
    fi
    echo "Java interpreter:      "$java
    echo "Use catalogs:          "$use_catalogs
    if $use_catalogs ; then 
	echo "Catalog file list:     "$cat_file_list
	echo "Catalog debug level:   "$cat_debug_level
	echo "Prefer catalog sysids  "$cat_override_val
    fi
    [ -n "$user_props" ] &&  echo "User Properties:       "$user_props
    echo "CLASSPATH:             "$CLASSPATH
    echo
    echo "Command issued: "
    echo "$cmd_line"
    echo
fi

## ----------------------------------------------------------------------
## just Do It

eval $cmd_line 

exit 0
