#!/bin/bash
# ======================================================================
#
# ENV INIT
#
# This is a helper tool for build processes with java and maven.
# It sets a custom java and maven version
#
# ----------------------------------------------------------------------
# 2024-02-18  first lines  <axel.hahn@unibe.ch>
# ======================================================================

cd "$( dirname "${BASH_SOURCE[0]}")" || exit 1

typeset -A aJava
typeset -A aMaven

USAGE="
This is a helper script to set the shell environment
for a wanted version of java and maven.

SYNTAX: source $0 [options]

OPTIONS:
    -j|--java <version>     Set Java version
    -m|--maven <version>    Set Maven version
    -h|--help               Show this help
"


if [ "$#" -eq 0 ]; then
    echo "ERROR: parameter required. Use -h for help."
    exit 2
fi

. "env_init.sh.cfg" || exit 3

# ----------------------------------------------------------------------

while [[ "$#" -gt 0 ]]; do case $1 in

    -h|--help)
        echo "$USAGE";
        echo "Java versions:"
        for v in "${!aJava[@]}"
        do
            echo "    $v ... ${aJava[$v]}"
        done
        echo
        echo "Maven versions:"
        for v in "${!aMaven[@]}"
        do
            echo "    $v ... ${aMaven[$v]}"
        done
        echo
        exit 0
        ;;

    -j|--java)
        if [ -z "${aJava[$2]}" ]; then
            echo "ERROR: java version $2 is unknown on this system"
            exit 4
        fi
        if [ ! -x "${aJava[$2]}/bin/java" ]; then
            echo "ERROR: Path for java version $2 is wrong - ${aJava[$2]}/bin/java not executable"
            exit 5
        fi
        echo ">>> Set JAVA version $2" 
        export JAVA_HOME="${aJava[$2]}"
        export PATH="${aJava[$2]}/bin:${PATH}"

        echo "\$ java --version"
        java --version
        echo
        shift; shift;
        ;;

    -m|--maven)
        if [ -z "${aMaven[$2]}" ]; then
            echo "ERROR: maven version $2 is unknown on this system"
            exit 6
        fi
        if [ ! -x "${aMaven[$2]}/bin/mvn" ]; then
            echo "ERROR: Path for mvn version $2 is wrong - ${aMaven[$2]}/bin/mvn not executable"
            exit 7
        fi
        echo ">>> Set maven version $2" 
        export PATH="${aMaven[$2]}/bin:${PATH}"

        echo "\$ mvn --version"
        mvn --version
        echo
        shift; shift;
        ;;

    *) if grep "^-" <<< "$1" >/dev/null ; then
        echo; echo "ERROR: Unknown parameter: $1"; echo "Use -h for help."; exit 8
       fi
       break;
       ;;

esac; done

if [ -n "$*" ]; then
    echo "ERROR: No parameter supported. Use -h for help."
    exit 9
fi

# ----------------------------------------------------------------------
