#!/bin/sh

# Portions of this file Copyright 1999-2005 University of Chicago
# Portions of this file Copyright 1999-2005 The University of Southern California.
#
# This file or a portion of this file is licensed under the
# terms of the Globus Toolkit Public License, found at
# http://www.globus.org/toolkit/download/license.html.
# If you redistribute this file, with or without
# modifications, you must include this notice in the file.

TMPLTAR="globus_wsrf_bindings_template.tar"
TMPLTARGZ="${TMPLTAR}.gz"
FTMPLTAR="${GLOBUS_LOCATION}/share/globus_c_wsrf_cgen/${TMPLTARGZ}"

if test -z "${GLOBUS_LOCATION}"; then
    echo ""
    echo "ERROR: Please set GLOBUS_LOCATION to the Globus installation"
    echo "       directory before running this script"
    echo ""
    exit 1
fi

if test -f ${GLOBUS_LOCATION}/libexec/globus-script-initializer; then
    . ${GLOBUS_LOCATION}/libexec/globus-script-initializer
fi

if test -f ${GLOBUS_LOCATION}/libexec/globus-sh-tools.sh &&
    test -f ${GLOBUS_LOCATION}/libexec/globus-sh-tools-vars.sh; then
    . ${GLOBUS_LOCATION}/libexec/globus-sh-tools.sh
fi

GL=${GLOBUS_LOCATION}
BINDIR=${GL}/bin
TMPLDIR=${GL}/share/globus_c_wsrf_cgen

PROGRAM_NAME=`echo $0 | sed -e "s|.*/||g"`

short_usage="$PROGRAM_NAME [-help][-s <package name>][-sn <service name>] \\
                 [-p <prefix file>][-P <prefix>][-r <relative path>] \\
                 [-d <output dir>][-N <namespace>][-n <file>] \\
                 [-G <namespace>][-g <file>][-np][-nk][-nf <function>][-ns] \\
                 <wsdl schema>"

long_usage()
{
    cat >&2 <<EOF

${short_usage}

    This command generates client side bindings in C from a WSDL schema file.

    Optional arguments:

     -help, -usage          : displays this message
     -s <package name>      : name used to create the package.  Defaults to
                              the service name from the WSDL schema. This
                              argument is required, unless -no-package is
                              specified.
     -sn <service name>     : overrides the name of the service defined
                              in the wsdl address element (but not the path).
			      This argument can only be used if one
			      service is defined in the WSDL schema files
			      passed in to the program.
     -p <file>              : location of the Namespace to Prefix mappings
     -P <prefix map>        : additional Namespace to Prefix mapping specified
                              on the command line.  This argument should be
                              be formatted as <prefix>=<namespace>.
     -N <namespace>         : Namespace to generate types for.  -N arguments
                              limit which types are generated.  Multiple
                              -N arguments can be combined with -n args.
                              With -N or -n arguments, -G and -g arguments 
                              are ignored.
     -n <file>              : File with Namespaces to generate types for.
                              One namespace per line.  See -N for further info.
     -G <namespace>         : Namespace to NOT generate types for.  If -N
                              or -n are specified, -G arguments are ignored.
     -g <file>              : File with Namespaces to NOT generate types for.
                              If -N or -n are specified, -g arguments are 
                              ignored.
     -r <relative path>     : the relative path where generated headers are
                              install into.  \$GL/include/<flavor>/<relpath>
     -d <output dir>        : directory to put the generated files in
     -no-package
     -np                    : No package creation.  Just generate files.
     -no-tarball
     -nb                    : Package files are created, but no package 
                              tarball is generated.  -np implies -nt
     -no-func <func>
     -nf <func>             : No generation of the function <func>.  e.g.
                              wsnt_TopicExpressionType_deserialize.  This
                              option is useful if you want to write your
                              own marshalling functions for a given type.
     -no-skel
     -nk                    : No skeleton source file generation
     -no-service
     -ns                    : No service.  Only generate client bindings 
                              and types.  -ns implies -nk.
     -no-client
     -nc                    : No client.  Only generate service bindings 
                              and types.  
     -no-types
     -nt                    : No types.  Only generate client and
                              service bindings.

    Required Argument:
     <wsdl schema>          : the WSDL schema to generate client side bindings

EOF
}

if test ! -f ${GLOBUS_LOCATION}/libexec/globus-args-parser-header; then
    echo ""
    echo "Failed to source file: ${GLOBUS_LOCATION}/libexec/globus-args-parser-header"
    echo ""
    exit 1
fi

. ${GLOBUS_LOCATION}/libexec/globus-args-parser-header $@

bailout ()
{
    if [ -z "${beenhere}" ]; then
        beenhere=yes
        echo ""
        echo "    The binding generation process was interrupted."
        echo "    Cleaning up..."
    fi
    exit 1
}
trap bailout 1 2 3 6 15

if test ! -x ${BINDIR}/globus-wsdl-parser; then
    echo ""
    echo "${BINDIR}/globus-wsdl-parser executable does not exist or does not have valid permissions"
    echo ""
    exit 1
fi

ARGS=""
while [ -n "$1" ]; do
    case "$1" in
        -help | -usage)
            long_usage
	    exit 1
            ;;
        -s)
	    package_name=${2}
            shift ; shift
            ;;
	-sn)
	    service_name=${2}
	    shift ; shift
	    ;;
        -r)
            relpath=${2}
            shift ; shift
            ;;
        -p | -P | -I | -g | -G | -n | -N)
            ARGS="$ARGS ${1} ${2}"
	    shift ; shift
            ;;
        -d)
            OUTDIR="${2}"
            shift ; shift
            ;;
        -no-package | -np)
            SKIP=1
            shift
            ;;
        -no-tarball | -nb)
            NOTARBALL=1
            shift
            ;;
        -gg)
            IGNORE=1
            shift
            ;;
        -dr)
            DRYRUN=1
            shift
            ;;
        -no-skel | -nk)
            SKIPSKELGEN=1
            shift
            ;;
        -no-service | -ns)
            NOSERVICE=1
            shift
            ;;
        -no-client | -nc)
            NOCLIENT=1
            shift
            ;;
        -no-types | -nt)
            NOTYPES=1
            shift
            ;;
        -no-func | -nf)
            SKIPFUNCS="${SKIPFUNCS} ${2}"
            shift ; shift
            ;;
        -flavor | -fl)
            FLAVOR="${2}"
            shift ; shift
            ;;
        -*)
            globus_args_unrecognized_option $1
            ;;
        *)
            schema_files="${schema_files} ${1}"
            shift
            ;;
    esac
done

if test -z "${package_name}" && test -z "${SKIP}"; then
    echo ""
    echo "ERROR: Required package name argument (-s <name>) not specified"
    echo ""
    cat >&2 <<EOF

${short_usage}

EOF

    exit 1
fi

if test -z "${FLAVOR}" && test -z "${SKIP}" && test -z "${NOTARBALL}"; then
    FLAVOR=`ls ${GLOBUS_LOCATION}/etc/globus_packages/globus_core/*dev.format |\
            ${GLOBUS_SH_SED-sed} -e "s|.*/\(.*\)dev.format|\1|"`
    if test -z "${FLAVOR}"; then
        echo ""
        echo "ERROR: Could not determine a usable flavor"
        echo ""
        cat >&2 <<EOF

${short_usage}

EOF
        exit 1
    fi
fi

if test -z "${schema_files}"; then
	echo ""
	echo "ERROR: No schema file specified"
	echo ""
    cat >&2 <<EOF

${short_usage}

EOF

	exit 1
fi

if test ! -z "${service_name}"; then
        ARGS="${ARGS} -V servicename=${service_name}"
else
        ARGS="${ARGS} -V servicename=undefined"
fi

if test ! -z "${package_name}"; then
	ARGS="${ARGS} -V packagename=${package_name}"
else
        ARGS="${ARGS} -V packagename=undefined"
fi

if test ! -z "${relpath}"; then
	ARGS="${ARGS} -V includepath=${relpath}"
else
        ARGS="${ARGS} -V includepath=undefined"
fi

if test ! -z "${SKIPSKELGEN}"; then
        ARGS="${ARGS} -V skipskelgen=${SKIPSKELGEN}"
else
    ARGS="${ARGS} -V skipskelgen=undefined"
fi

if test ! -z "${NOSERVICE}"; then
    ARGS="${ARGS} -V noservice=${NOSERVICE}"
else
    ARGS="${ARGS} -V noservice=undefined"
fi

if test ! -z "${NOCLIENT}"; then
    ARGS="${ARGS} -V noclient=${NOCLIENT}"
else
    ARGS="${ARGS} -V noclient=undefined"
fi

if test ! -z "${NOTYPES}"; then
    ARGS="${ARGS} -V notypes=${NOTYPES}"
else
    ARGS="${ARGS} -V notypes=undefined"
fi

if test ! -z "${SKIPFUNCS}"; then
    ARGS="${ARGS} -V skipfuncs=\"${SKIPFUNCS}\""
else
    ARGS="${ARGS} -V skipfuncs=undefined"
fi

if test -z "${OUTDIR}"; then
    OUTDIR="."
fi

if test ! -f "${FTMPLTAR}"; then
    echo ""
    echo "Invalid installation of globus_c_wsrf_cgen package.  ${FTMPLTAR} not found."
    echo ""
    exit 1
fi

reldir=`echo ${OUTDIR} | sed -e "s|/.*||"`
if test -n "${reldir}"; then
    CWD=`pwd`
    OUTDIR=${CWD}/${OUTDIR}
fi

if test ! -d "${OUTDIR}"; then
    mkdir ${OUTDIR}
    res=$?
    if test $res != 0; then
        echo ""
        echo "Failed to create output directory ${OUTDIR}"
        echo ""
        exit 1
    fi
fi

if test -z "${SKIP}" \
        && test -z "${SKIP_METADATA_MERGE}" \
        && test -z "${DRYRUN}" \
        && test -f pkgdata/pkg_data_src.gpt; then
    cp pkgdata/pkg_data_src.gpt $OUTDIR/pkgdata/pkg_data_src.gpt.save
fi

if test -z "${SKIP}"; then

    cp ${FTMPLTAR} ${OUTDIR}
    CWD=`pwd`

    cd ${OUTDIR}

    if test ! -f "${TMPLTAR}"; then
        gunzip -f ${TMPLTARGZ}
        res=$?
        if test $res != 0; then
            echo ""
            echo "Error: Failed to decompress client template tarball: $TMPLTARGZ"
            echo ""
            exit $res
        fi
    fi

    tar xf ${TMPLTAR}
    res=$?
    if test $res != 0; then
        echo ""
        echo "Error: Failed to extract client template files from tarball: $TMPLTAR"
        echo ""
        exit $res
    fi

    cd ${CWD}

fi

if test -z "${SKIP}"; then
    templatefile=${TMPLDIR}/package-gen.tmpl
else
    templatefile=${TMPLDIR}/gen-stubs-doclit.tmpl
fi

if test -z "${IGNORE}"; then
    IGNORE_ARGS="-g ${TMPLDIR}/WSRF-NS.ignore"
else
    IGNORE_ARGS=""
fi

if test -n "${DRYRUN}"; then
    PRECMD="echo"
else
    PRECMD=""
fi

${PRECMD} ${BINDIR}/globus-wsdl-parser -I ${TMPLDIR} -I ${OUTDIR} -p ${TMPLDIR}/NStoP_default.properties  -d ${OUTDIR} ${IGNORE_ARGS} ${ARGS} ${templatefile} ${schema_files}
res=$?
if test $res != 0; then
    exit $res
fi

if test -z "${SKIP}" \
    && test -z "${SKIP_METADATA_MERGE}" \
    && test -f pkgdata/pkg_data_src.gpt.save \
    && test -z "${DRYRUN}"; then
    ${GLOBUS_LOCATION}/libexec/globus-cgen-merge-pkgdata \
            pkgdata/pkg_data_src.gpt.save \
            $OUTDIR/pkgdata/pkg_data_src.gpt.in \
            $OUTDIR/pkgdata/pkg_data_src.gpt.in.tmp

    mv -f   $OUTDIR/pkgdata/pkg_data_src.gpt.in.tmp \
            $OUTDIR/pkgdata/pkg_data_src.gpt.in
            
fi

if test -z "${SKIP}" && test -z "${DRYRUN}"; then

    cd ${OUTDIR}

    read pname < ${OUTDIR}/PACKAGENAME
    export pname

    SERVICE_MAKEFILES=""
    SERVICE_CONFIG_FILES=""
    SERVICE_LIST=""

    if test -z "${NOSERVICE}"; then

        while read sname spath; do

            i=0
            if test -n "${service_name}" && 
	       test "${i}" -gt "0"; then

	       echo ""
	       echo "ERROR: Cannot use -sn with multiple service definitions."
	       echo ""
	       exit 1
	    fi

	    i=`expr ${i} + 1`
        done < ${OUTDIR}/SERVICES_LIST
    fi

    echo ""
    echo "Creating Bindings Package"
    echo ""

    ./bootstrap > bootstrap.log 2>&1
    if test -z "${NOTARBALL}"; then

        ./configure --with-flavor=${FLAVOR} > configure.log 2>&1
        res=$?
        if test $res != 0; then
            echo ""
            echo "Error: Failed to configure build package"
            echo "       See ${OUTDIR}/configure.log for further info"
            echo ""
            exit 1
        fi

        rm -f *_bindings-*.tar.gz 
        res=$?
        # for now ignore failure

        make dist > make_dist.log 2>&1
        res=$?
        if test $res != 0; then
            echo ""
            echo "Error: Failed to make build package"
            echo "       See ${OUTDIR}/make_dist.log for further info"
            echo ""
            exit 1
        fi

        PKG=`ls *bindings-*.tar.gz`
        echo "A new package has been created at ${OUTDIR}/${PKG}"
        echo "To install, use the following command:"
        echo ""
        echo "\$GLOBUS_LOCATION/sbin/gpt-build ${OUTDIR}/${PKG} <flavor>"
        echo ""
    fi

    cd ${CWD}
fi

