#!/bin/bash

source "$ROOT_PATH"/scripts/common.sh
if $BUILD_FROM_SCRATCH ; then
  if [ ! -z "$DIR_TO_BUILD" ]; then
  cd $DIR_TO_BUILD
  fi
  if [ ! -z "$VERSION_TO_DEPLOY" ]; then
  yq -e ".project.version = \"${VERSION_TO_DEPLOY}\"" -i pom.xml
  yq -p xml '.project.version' pom.xml
  fi

  if [ -z "$SONAR_ARGS" ] || [ "$RUN_SONAR_SCAN" = "false" ]; then
  export SONAR_ARGS=""
  fi

  if [ -z "$MVN_PROFILE" ]; then
      pwd
      mvn_command="mvn clean install $SONAR_ARGS $MAVEN_EXTRA_ARGS"
  else
      pwd
      mvn_command="mvn clean install $SONAR_ARGS "$MVN_PROFILE" $MAVEN_EXTRA_ARGS"
  fi

  echo_green_bg "mvn command = $mvn_command"
  mvn_output=$($mvn_command)
  maven_exit_code=$?
  touch mvn.log
  rm -f mvn.log
  touch mvn.log
  echo "$mvn_output" > mvn.log
  if grep "BUILD FAILURE" mvn.log; then
  seperator="\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-"
  error_message=$(tail -n +"$(grep -n "$seperator" mvn.log | tail -1 | cut -d":" -f1)" mvn.log | head -n2 | tail -n1)
      error_message=$(echo $error_message | sed 's@[][]@ @g')
      echo "error message: $error_message"
      echo "MESSAGE_OF_FAIL=$error_message" >> $GITHUB_ENV
      echo "BUILD_FAILED=true" >> $GITHUB_ENV
  cat mvn.log
      rm -f mvn.log
  exit 1
  fi
  cat mvn.log
  rm -f mvn.log
  if [[ "$maven_exit_code" -ne 0 ]] ; then
  echo "mvn command fails with exit code $maven_exit_code"
  error_message="general maven error"
  echo "MESSAGE_OF_FAIL=$error_message" >> $GITHUB_ENV
  echo "BUILD_FAILED=true" >> $GITHUB_ENV
  exit 1
  fi
  if [[ "$?" -ne 0 ]] ; then
  echo 'ERROR in maven clean install. exiting'; exit "$?"
  fi
fi

