# -*- mode:sh -*-
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you 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,
: ${GROOVY_HOME="/usr/local/share/java/groovy"}
[ -z "${JAVA_HOME}" ] && JAVA_HOME="`env JAVAVM_DRYRUN=yes /usr/local/bin/java | grep '^JAVA_HOME' | cut -c11-`"
# 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.
# ----------------------------------------------------------------------------

##############################################################################
##                                                                          ##
##  Groovy JVM Bootstrap for UN*X                                           ##
##                                                                          ##
##############################################################################

##
## $Revision$
## $Date$
##

PROGNAME=`basename "$0"`

#DIRNAME=`dirname "$0"`

SCRIPT_PATH="$0"

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn ( ) {
    echo "${PROGNAME}: $*"
}

die ( ) {
    warn "$*"
    exit 1
}

earlyInit ( ) {
    return
}

lateInit ( ) {
    return
}

GROOVY_STARTUP="$HOME/.groovy/startup"
if [ -r "$GROOVY_STARTUP" ] ; then
    . "$GROOVY_STARTUP"
fi

earlyInit

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;; 
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
  NONSTOP* )
    nonstop=true
    ;;
esac

if [ "$1" = "-cp" -o "$1" = "-classpath" -o "$1" = "--classpath" ] ; then
    CP=$2
    shift 2
fi

# Attempt to set JAVA_HOME if it's not already set.
if [ -z "$JAVA_HOME" ] ; then
    if $darwin ; then 
        [ -z "$JAVA_HOME" -a -f "/usr/libexec/java_home" ] && export JAVA_HOME=`/usr/libexec/java_home`
        [ -z "$JAVA_HOME" -a -d "/Library/Java/Home" ] && export JAVA_HOME="/Library/Java/Home"
        [ -z "$JAVA_HOME" -a -d "/System/Library/Frameworks/JavaVM.framework/Home" ] && export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Home"
    else
        javaExecutable="`which javac`"
        [ -z "$javaExecutable" -o "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ] && die "JAVA_HOME not set and cannot find javac to deduce location, please set JAVA_HOME."
        # readlink(1) is not available as standard on Solaris 10.
        readLink=`which readlink`
        [ `expr "$readLink" : '\([^ ]*\)'` = "no" ] && die "JAVA_HOME not set and readlink not available, please set JAVA_HOME."
        javaExecutable="`readlink -f \"$javaExecutable\"`"
        javaHome="`dirname \"$javaExecutable\"`"
        javaHome=`expr "$javaHome" : '\(.*\)/bin'`
        JAVA_HOME="$javaHome"
        export JAVA_HOME

    fi
fi

# For Cygwin, ensure paths are in UNIX format before anything is touched.
if $cygwin ; then
    [ -n "$GROOVY_HOME" ] && GROOVY_HOME=`cygpath --unix "$GROOVY_HOME"`
    [ -n "$JAVACMD" ] && JAVACMD=`cygpath --unix "$JAVACMD"`
    [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
    [ -n "$CP" ] && CP=`cygpath --path --unix "$CP"`
else
    if [ -n "$GROOVY_HOME" -a "`expr "$GROOVY_HOME":'\/$'`" ] ; then
        GROOVY_HOME=`echo $GROOVY_HOME | sed -e 's/\/$//'`
    fi
fi

#  For MSYS, ensure paths are in appropriate format.
if $msys
then
    [ -n "$JAVA_HOME" ] && JAVA_HOME=`( cd "$JAVA_HOME" ; pwd )`
fi

# Attempt to set GROOVY_HOME if it is not already set.
if [ -z "$GROOVY_HOME" -o ! -d "$GROOVY_HOME" ] ; then
    # Resolve links: $0 may be a link to groovy's home.
    PRG="$0"
    # Need this for relative symlinks.
    while [ -h "$PRG" ] ; do
        ls=`ls -ld "$PRG"`
        link=`expr "$ls" : '.*-> \(.*\)$'`
        if expr "$link" : '/.*' > /dev/null; then
            PRG="$link"
        else
            PRG=`dirname "$PRG"`"/$link"
        fi
    done
    SAVED="`pwd`"
    cd "`dirname \"$PRG\"`/.."
    GROOVY_HOME="`pwd -P`"
    cd "$SAVED"
fi

# Set the default Groovy config if no specific one is mentioned.
if [ -z "$GROOVY_CONF" ] ; then
    GROOVY_CONF="$GROOVY_HOME/conf/groovy-starter.conf"
fi
STARTER_CLASSPATH="$GROOVY_HOME/lib/groovy-2.4.16.jar"

# Create the final classpath. Setting a classpath using the -cp or -classpath option means not to use the
# global classpath. Groovy behaves then the same as the java interpreter
if [ -n "$CP" ] ; then
    CP="$CP":.
elif [ -n "$CLASSPATH" ] ; then
    CP="$CLASSPATH":.
else
    CP=.
fi

# Determine the Java command to use to start the JVM.
if [ -z "$JAVACMD" ] ; then
    if [ -n "$JAVA_HOME" ] ; then
        if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
            # IBM's JDK on AIX uses strange locations for the executables
            JAVACMD="$JAVA_HOME/jre/sh/java"
        else
            JAVACMD="$JAVA_HOME/bin/java"
        fi
    else
        JAVACMD="java"
    fi
fi
if [ ! -x "$JAVACMD" ] ; then
    die "JAVA_HOME is not defined correctly, can not execute: $JAVACMD"
fi
if [ -z "$JAVA_HOME" ] ; then
    warn "JAVA_HOME environment variable is not set"
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query businessSystem maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# Setup Profiler
useprofiler=false
if [ "$PROFILER" != "" ] ; then
    if [ -r "$PROFILER" ] ; then
        . $PROFILER
        useprofiler=true
    else
        die "Profiler file not found: $PROFILER"
    fi
fi

# For Darwin, use classes.jar for TOOLS_JAR
TOOLS_JAR="$JAVA_HOME/lib/tools.jar"
#if $darwin; then
#    TOOLS_JAR="/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Classes/classes.jar"
#fi

# For Darwin, add GROOVY_APP_NAME to the JAVA_OPTS as -Xdock:name
if $darwin; then
    JAVA_OPTS="$JAVA_OPTS -Xdock:name=$GROOVY_APP_NAME -Xdock:icon=$GROOVY_HOME/lib/groovy.icns"
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    GROOVY_HOME=`cygpath --mixed "$GROOVY_HOME"`
    JAVA_HOME=`cygpath --mixed "$JAVA_HOME"`
    GROOVY_CONF=`cygpath --mixed "$GROOVY_CONF"`
    CP=`cygpath --path --mixed "$CP"`    
    TOOLS_JAR=`cygpath --mixed "$TOOLS_JAR"`
    STARTER_CLASSPATH=`cygpath --path --mixed "$STARTER_CLASSPATH"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GROOVY_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GROOVY_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        if [ $CHECK -ne 0 ] ; then
            patched=`cygpath --path --ignore --mixed "$arg"`
        else
            patched="$arg"
        fi
        if [ x"$BASH" = x ]; then
            eval `echo args$i`="\"$arg\""
        else
            args[$i]="$patched"
        fi
        i=`expr $i + 1`
    done

    if [ x"$BASH" = x ]; then
        case $i in
            0) set -- ;;
            1) set -- "$args0" ;;
            2) set -- "$args0" "$args1" ;;
            3) set -- "$args0" "$args1" "$args2" ;;
            4) set -- "$args0" "$args1" "$args2" "$args3" ;;
            5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
            6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
            7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
            8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
            9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
        esac
    else
        set -- "${args[@]}"
    fi
fi

startGroovy ( ) {
    CLASS=$1
    shift
    # Start the Profiler or the JVM
    if $useprofiler ; then
        runProfiler
    else
        eval exec "\"\$JAVACMD\"" $JAVA_OPTS \
            -classpath "\"\$STARTER_CLASSPATH\"" \
            -Dscript.name="\"\$SCRIPT_PATH\"" \
            -Dprogram.name="\"\$PROGNAME\"" \
            -Dgroovy.starter.conf="\"\$GROOVY_CONF\"" \
            -Dgroovy.home="\"\$GROOVY_HOME\"" \
            -Dtools.jar="\"\$TOOLS_JAR\"" \
            $STARTER_MAIN_CLASS \
            --main $CLASS \
            --conf "\"\$GROOVY_CONF\"" \
            --classpath "\"\$CP\"" \
            "\"\$@\""
    fi
}

STARTER_MAIN_CLASS=org.codehaus.groovy.tools.GroovyStarter

lateInit
