#!/usr/bin/env bash

# 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.

SOURCE=$0;
SCRIPT=`basename "$SOURCE"`;
while [ -h "$SOURCE" ]; do
    SCRIPT=`basename "$SOURCE"`;
    LOOKUP=`ls -ld "$SOURCE"`;
    TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`;
    if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then
        SOURCE=${TARGET:-.};
    else
        SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
    fi;
done;

BIN=$(cd $(dirname "$SOURCE"); pwd)
LOGGING_OPTS="-Dlog4j.configuration=log4j-cli.xml"

# Set cygwin to true if running on Cygwin
cygwin=false;
case "`uname`" in
	CYGWIN*) cygwin=true;
esac

if [ -e ~/.whirr/credentials ]; then
    . ~/.whirr/credentials
elif [ -e $BIN/../conf/credentials ]; then
    . $BIN/../conf/credentials
fi

# Override cloud provider credentials as needed
export WHIRR_PROVIDER=${WHIRR_PROVIDER:-$PROVIDER}
export WHIRR_IDENTITY=${WHIRR_IDENTITY:-$IDENTITY}
export WHIRR_CREDENTIAL=${WHIRR_CREDENTIAL:-$CREDENTIAL}

# Override blob store credentials as needed
export WHIRR_BLOBSTORE_PROVIDER=${WHIRR_BLOBSTORE_PROVIDER:-$BLOBSTORE_PROVIDER}
export WHIRR_BLOBSTORE_IDENTITY=${WHIRR_BLOBSTORE_IDENTITY:-$BLOBSTORE_IDENTITY}
export WHIRR_BLOBSTORE_CREDENTIAL=${WHIRR_BLOBSTORE_CREDENTIAL:-$BLOBSTORE_CREDENTIAL}

# Build the classpath
if [ -d "$BIN/../cli/target/lib" ]; then
  CLASSPATH="$BIN/../conf/:$BIN/..:$BIN/../cli/target/lib/*:$BIN/../cli/target/*"
else
  CLASSPATH="$BIN/../conf/:$BIN/..:$BIN/../lib/*"
fi

# Java classpath doesn't understand cygwin paths, thus converting the CLASSPATH into 
# Windows style path.
if $cygwin; then 
  CLASSPATH=`cygpath -wp $CLASSPATH`;
fi

# Start the application
java $LOGGING_OPTS $WHIRR_CLI_OPTS -cp "$CLASSPATH" org.apache.whirr.cli.Main "$@"
 
