#!/bin/bash
LOG_NAME=$1
PROJECT_NAME=$2
FOLDER_NAME=$3
MAVEN_SETTINGS=$4

echo "LOG_NAME=$LOG_NAME"
echo "FOLDER_NAME=$FOLDER_NAME"
echo "PROJECT_NAME=$PROJECT_NAME"
echo "MAVEN_SETTINGS=$MAVEN_SETTINGS"

MAVEN_BUILD=maven.build

# Kill the server running the springboot jar
pkill java

# Run a maven build to generate the new jar
cd /root/app

if [[ "$IN_K8" == "true" ]]; then
        MAVEN_REPO_CACHE_PATH=/root/app/localm2cache.zip
else
        MAVEN_REPO_CACHE_PATH=/tmp/localm2cache.zip
fi

if [ -f $MAVEN_REPO_CACHE_PATH ]; then
    echo "Extracting maven m2 cache for $PROJECT_NAME"
    $JAVA_HOME/bin/jar -xf $MAVEN_REPO_CACHE_PATH
    rm -f $MAVEN_REPO_CACHE_PATH
    echo "Finished extracting maven m2 cache for $PROJECT_NAME"	
fi

echo "Running Maven build for $PROJECT_NAME"

# copy settings.xml if present
if [[ -f settings.xml ]]; then
    mkdir -p /root/.m2/
    mv settings.xml /root/.m2/
fi

echo "mvn -Dmaven.repo.local=/root/app/.m2/repository -f ./pom.xml package -Dmaven.test.skip=true $MAVEN_SETTINGS --log-file "/root/logs/$MAVEN_BUILD.log""
mvn -Dmaven.repo.local=/root/app/.m2/repository -f ./pom.xml package -Dmaven.test.skip=true $MAVEN_SETTINGS --log-file "/root/logs/$MAVEN_BUILD.log"

# remove settings.xml after build
rm -f /root/.m2/settings.xml

if [[ $? -ne 0 ]]; then
    # Exit if maven build failed
    echo "Maven build failed for $PROJECT_NAME"
    exit 1;
fi
echo "Maven build successful for $PROJECT_NAME"

# Change the owner of the files that generated by maven build so that theia (the user of theia container is 1001) can delete those files
chown -R 1001 .m2
chown -R 1001 target

# Determine the jar to copy over
TARGET_JAR=$(sed -n -e 's/^.*Building jar: //p' /root/logs/$MAVEN_BUILD.log)

# If we couldn't find the jar in the default location, see if there are any jars containing SNAPSHOT
if [[ ! -f $TARGET_JAR ]]; then
    TARGET_JAR=target/$(ls target/ | grep 'SNAPSHOT.jar' | head -n1)
fi

# If the target jar still isn't found, see if a jar containing the project name exists
if [[ ! -f $TARGET_JAR ]]; then
    TARGET_JAR=target/$(ls target/ | grep $PROJECT_NAME | head -n1)
fi

# Failover, grab the first jar under target
if [[ ! -f $TARGET_JAR ]]; then
    TARGET_JAR=target/$(ls target/*.jar | head -n1)
fi


# If there's already a Spring app running, kill it
APP_JAR=/root/app.jar
pkill -f "java -jar $APP_JAR"

# Copy the jar over
cp -rf $TARGET_JAR $APP_JAR
