#!/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.
#
set -e

SOURCES_DIR=/tmp/artifacts
SCRIPT_DIR=$(dirname "${0}")

mvn_install_dir="/usr/share/maven"

# Verify if mvn is installed
if [ ! -d ${mvn_install_dir} ] && ! command -v mvn > /dev/null 2>&1 ;
then
    echo "---> Maven not found, downloading and installing it"
    tar xzf "${SOURCES_DIR}"/apache-maven-"${MAVEN_VERSION}"-bin.tar.gz -C /usr/share
    mv /usr/share/apache-maven-"${MAVEN_VERSION}" ${mvn_install_dir}
else
    echo "---> Maven already present in the current context"
    # TODO: Remove this temporary solution in favor of the -DnoMavenVersionCheck flag once it's available
    # https://github.com/quarkusio/quarkus/issues/46105
    # Installs Maven Wrapper for version 3.8.6 in order to be compatible with the quarkus-maven-plugin minimum requirements (on Quarkus 3.15.3.1).
    echo "---> Installing Maven wrapper for Maven 3.8.6"
    cd "${MAVEN_HOME}"/bin
    mvn wrapper:wrapper -Dmaven=3.8.6 -Dtype=source
    echo "--> Validating Maven wrapper installation"
    ${MAVEN_CMD} --version
fi

mkdir "${KOGITO_HOME}"/.m2
cp -v "${SCRIPT_DIR}"/maven/* "${KOGITO_HOME}"/.m2
cp -v "${SCRIPT_DIR}"/added/* "${KOGITO_HOME}"/launch/
