#!/usr/bin/env bash
#   Copyright 2017 Otavio Rodolfo Piske
#
#   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.

cygwin=false
darwin=false
mingw=false

# OS specific support.  $var _must_ be set to either true or false.
case "$(uname)" in
    CYGWIN*) cygwin=true ;;
    MINGW*) mingw=true ;;
    Darwin*) darwin=true ;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched
if ${cygwin}; then
    : ${JAVA_HOME:=$(cygpath --unix "${JAVA_HOME}")}
    : ${CLASSPATH:=$(cygpath --path --unix "${CLASSPATH}")}
fi

if ${darwin}; then
    : ${JAVA_VERSION:="CurrentJDK"}
    : ${JAVA_HOME:="/System/Library/Frameworks/JavaVM.framework/Versions/${JAVA_VERSION}/Home"}
fi

# Installation paths
localDir="$(dirname $0)"
installDir="$(dirname "${localDir}")"

if [[ ${installDir} == "." ]] ; then
	installDir=".."
fi

MAESTRO_CLASSPATH=""

for jarfile in "${installDir}"/bin/*.jar ; do
    if [[ -z "${MAESTRO_CLASSPATH}" ]] ; then
        MAESTRO_CLASSPATH="${jarfile}"
    else
        MAESTRO_CLASSPATH="${MAESTRO_CLASSPATH}:${jarfile}"
    fi
done


for jarfile in "${installDir}"/lib/*.jar ; do
    if [[ -z "${MAESTRO_CLASSPATH}" ]] ; then
        MAESTRO_CLASSPATH="${jarfile}"
    else
        MAESTRO_CLASSPATH="${MAESTRO_CLASSPATH}:${jarfile}"
    fi
done

for jarfile in "${installDir}"/lib/ext/*.jar ; do
    if [[ -z "${MAESTRO_CLASSPATH}" ]] ; then
        MAESTRO_CLASSPATH="${jarfile}"
    else
        MAESTRO_CLASSPATH="${MAESTRO_CLASSPATH}:${jarfile}"
    fi
done


export MAESTRO_CLI_DEBUG_ARGS=""
if [[ "${MAESTRO_DEBUG}" == "y" ]] ; then
    MAESTRO_CLI_DEBUG_ARGS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
fi

mainClass="org.maestro.cli.main.MaestroCliMain"

java -classpath ${MAESTRO_CLASSPATH} ${MAESTRO_CLI_DEBUG_ARGS} \
    -Dorg.maestro.home="${installDir}" -Djava.awt.headless=true "${mainClass}" "$@"
