#!/bin/bash

call_maven() {
    local args=$1
    local maven_modules=$2
    local args_to_use="--show-version --strict-checksums $args"

    check_error "$maven_modules"
    if [ -z "${maven_modules}" ]; then
      return
    fi

    if [ "$(hasflag --settings -s)" ]; then
      args_to_use+=" -s $(readopt --settings -s)"
    fi

    pushd "$(appdir)" || echo ERROR: unable to change directory to "$(appdir)" exit > /dev/null

    if [ "EVERYTHING" == "${maven_modules}" ]; then
      _call_maven_internal "$args_to_use" "Building everything"
    else
      if [ "$(hasflag --dependencies -d)" ]; then
          args_to_use+=" -am"
      fi

      echo "Modules: $maven_modules"
      args_to_use+=" -Dbuild-selection -P"
      for module in $maven_modules; do
        if [ "${module}" != "test" ]; then
          args_to_use+="build-${module//:/},"
        fi
      done
      args_to_use=${args_to_use%?}
      _call_maven_internal "$args_to_use" "Building specified modules"
    fi

    popd || exit >/dev/null
}

_call_maven_internal() {
    echo "=============================================================================="
    echo "./mvnw $1 ### $2"
    echo "=============================================================================="
    ./mvnw $1
}
