#!/bin/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,
# 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.

#
# Apache Karaf Minho Build startup script
#
# Supported environment variables:
#
#   JAVA_HOME   (Optional) Points to a Java installation.
#

# OS specific support
cygwin=false;
mingw=false;
case "`uname`" in
  CYGWIN*) cygwin=true;;
  MINGW*) mingw=true;;
esac

# resolve links - $0 may be a link to minho-build'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

saveddir=`pwd`

MINHO_BUILD_HOME=`dirname "$PRG"`/..

# make it fully qualified
MINHO_BUILD_HOME=`cd "$MINHO_BUILD_HOME" && pwd`

cd "$saveddir"

# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if $cygwin || $mingw ; then
    [ -n "$JAVA_HOME" ] &&
        JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
fi

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"

        if [ ! -x "$JAVACMD" ] ; then
            echo "The JAVA_HOME environment variable is not defined correctly, so Apache Karaf Minho Build cannot be started." >&2
            echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" does not exist." >&2
            exit 1
        fi
    fi
else
    JAVACMD="`\\unset -f command; \\command -v java`"

    if [ ! -x "$JAVACMD" ] ; then
        echo "The java(1) command does not exist in PATH nor is JAVA_HOME set, so Apache Karaf Minho Build cannot be started." >&2
        exit 1
    fi
fi

# create CLASSPATH
for file in $MINHO_BUILD_HOME/lib/*.jar
do
    CLASSPATH=$CLASSPATH:$file
done

# For Cygwin and MinGW, switch paths to Windows format before running java(1) command
if $cygwin || $mingw ; then
    [ -n "$JAVA_HOME" ] &&
        JAVA_HOME=`cygpath --windows "$JAVA_HOME"`
    MINHO_BUILD_HOME=`cygpath --windows "$MINHO_BUILD_HOME"`
fi

exec "$JAVACMD" \
    -classpath "$CLASSPATH" \
    org.apache.karaf.minho.tooling.cli.Main "$@"