#!/bin/sh
# Copyright (c) 2013-2014 Red Hat, Inc.
#
# 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.
#
# Written by Mikolaj Izdebski <mizdebsk@redhat.com>

# 0. Setup sane shell environment
\unset IFS
\unalias -a
unset -f command
path="${PATH}"
export PATH="$(command -p getconf PATH):${PATH}"
unset LANG CDPATH
export LC_ALL=POSIX
set -e

# 1. Determine installation directory of XMvn
case "${0}" in
    *[\\/]*)
        home=$(dirname "${0}")/..
        ;;
    *)
        IFS=:
        for dir in $path; do
            if [ -z "${dir}" ]; then
                dir=.
            fi
            if [ -r "${dir}/${0}" ]; then
                home="${dir}"/..
                unset IFS
                break
            fi
        done

        echo "$0: Unable to find XMvn installation directory." >&2
        exit 1
        ;;
esac

# 2. Determine which tool was ran
tool=$(basename "${0}")
case "${tool}" in
    *bisect*)
        tool=bisect
        class=org.fedoraproject.xmvn.tools.bisect.BisectCli
        ;;
    *install*)
        tool=installer
        class=org.fedoraproject.xmvn.tools.install.cli.InstallerCli
        ;;
    *resolve*)
        tool=resolver
        class=org.fedoraproject.xmvn.tools.resolve.ResolverCli
        ;;
    *subst*)
        tool=subst
        class=org.fedoraproject.xmvn.tools.subst.SubstCli
        ;;
    *)
        class="${tool}"
esac

# 3. Set classpath
unset cp
for jar in "${home}/lib/${tool}"/*; do
    cp="${cp}${cp+:}${jar}"
done

# 4. Execute the tool
exec java -classpath "${cp}" "${class}" "${@}"