#!/bin/sh
#
# Mule Cloud Connector Development Kit
# Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Get the fully qualified path to the script
case $0 in
    /*)
        SCRIPT="$0"
        ;;
    *)
        PWD=`pwd`
        SCRIPT="$PWD/$0"
        ;;
esac

# Resolve the true real path without any sym links.
CHANGED=true
while [ "X$CHANGED" != "X" ]
do
    # Change spaces to ":" so the tokens can be parsed.
    SAFESCRIPT=`echo $SCRIPT | sed -e 's; ;:;g'`
    # Get the real path to this script, resolving any symbolic links
    TOKENS=`echo $SAFESCRIPT | sed -e 's;/; ;g'`
    REALPATH=
    for C in $TOKENS; do
        # Change any ":" in the token back to a space.
        C=`echo $C | sed -e 's;:; ;g'`
        REALPATH="$REALPATH/$C"
        # If REALPATH is a sym link, resolve it.  Loop for nested links.
        while [ -h "$REALPATH" ] ; do
            LS="`ls -ld "$REALPATH"`"
            LINK="`expr "$LS" : '.*-> \(.*\)$'`"
            if expr "$LINK" : '/.*' > /dev/null; then
                # LINK is absolute.
                REALPATH="$LINK"
            else
                # LINK is relative.
                REALPATH="`dirname "$REALPATH"`""/$LINK"
            fi
        done
    done

    if [ "$REALPATH" = "$SCRIPT" ]
    then
        CHANGED=""
    else
        SCRIPT="$REALPATH"
    fi
done

# $REALPATH denotes the full path to the script now. Go one level up to determine DEVKIT_HOME
DEVKIT_HOME="`dirname ${REALPATH}`"

CP=""
for JAR in ${DEVKIT_HOME}/lib/*.jar
do
    CP="${CP}:${JAR}"
done
ARCHETYPE_SCRIPT_FILE=/tmp/run-mule-cloud-connector-archetype.$$

# ask some questions and generate the scipt file that invokes the archetype
java -cp "${CP}" org.codehaus.groovy.tools.GroovyStarter \
    --main groovy.ui.GroovyMain \
    ${DEVKIT_HOME}/bin/CreateArchetypeProperties.groovy ${ARCHETYPE_SCRIPT_FILE}

# now run the archetype
. ${ARCHETYPE_SCRIPT_FILE}

rm ${ARCHETYPE_SCRIPT_FILE}
