#!/bin/sh
# Maven Wrapper script
# Downloads and runs Maven if not already installed

set -e

MAVEN_WRAPPER_JAR=".mvn/wrapper/maven-wrapper.jar"
WRAPPER_PROPERTIES=".mvn/wrapper/maven-wrapper.properties"

if [ -f "$WRAPPER_PROPERTIES" ]; then
    DIST_URL=$(grep "distributionUrl" "$WRAPPER_PROPERTIES" | cut -d'=' -f2- | tr -d '\r')
fi

if [ -z "$DIST_URL" ]; then
    DIST_URL="https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip"
fi

MAVEN_HOME="${HOME}/.m2/wrapper/dists/apache-maven-3.9.6"

if [ ! -f "${MAVEN_HOME}/bin/mvn" ]; then
    echo "Downloading Maven..."
    mkdir -p "${MAVEN_HOME}"
    TMPFILE=$(mktemp)
    curl -fsSL "$DIST_URL" -o "$TMPFILE"
    unzip -qo "$TMPFILE" -d "${MAVEN_HOME}/.."
    rm -f "$TMPFILE"
fi

exec "${MAVEN_HOME}/bin/mvn" "$@"
