#!/bin/bash

MVN=mvn

function run_mvn() {
  PROFILES=$1
  PHASES=$2
  SWITCH=$3
  if [ -z "$PROFILES" ]; then
    if [ -z "${SWITCH}" ]; then
      if [ -z "${JDK8}" ]; then
        ${MVN} -B -U ${PHASES}
      else
        ${MVN} -B -U -Pjdk8 ${PHASES}
      fi
    else
      if [ -z "${JDK8}" ]; then
        ${MVN} -B -U ${PHASES} ${SWITCH}
      else
        ${MVN} -B -U -Pjdk8 ${PHASES} ${SWITCH}
      fi
    fi
  else
    if [ -z "${SWITCH}" ]; then
      if [ -z "${JDK8}" ]; then
        ${MVN} -B -U -P${PROFILES} ${PHASES}
      else
        ${MVN} -B -U -P${PROFILES},jdk8 ${PHASES}
      fi
    else
      if [ -z "${JDK8}" ]; then
        ${MVN} -B -U -P${PROFILES} ${PHASES} ${SWITCH}
      else
        ${MVN} -B -U -P${PROFILES},jdk8 ${PHASES} ${SWITCH}
      fi
    fi
  fi
}

if [ "$1" = "--with-jdk8" ]; then
  JDK8="true"
  CMD=$2
  ARG=$3
else
  CMD=$1
  ARG=$2
fi

case "$CMD" in
  clean)
    run_mvn "integration,benchmark,profile,distribution" "clean"
    ;;
  javadoc)
    run_mvn "" "javadoc:javadoc"
    ;;
  package)
    run_mvn "distribution" "package"
    ;;
  verify)
    run_mvn "distribution" "verify"
    ;;
  install)
    run_mvn "distribution" "install"
    ;;
  versions-set)
    if [ -z "${ARG}" ]; then
      echo "USAGE: `basename $0` versions-set <version>"
      exit 1
    fi
    run_mvn "distribution" "versions:set" "-DnewVersion=${ARG} -DgenerateBackupPoms=false"
    ;;
  versions-display-dependency)
    run_mvn "integration,benchmark,profile,distribution" "versions:display-dependency-updates"
    ;;
  versions-display-plugin)
    run_mvn "integration,benchmark,profile,distribution" "versions:display-plugin-updates"
    ;;
  deploy)
    if [ -z "${ARG}" ]; then
      echo "USAGE: `basename $0` deploy <repo-directory>"
      exit 1
    fi
    run_mvn "" clean
    run_mvn "" "deploy" "-DaltDeploymentRepository=snapshot::default::file://${ARG}"
    ;;
  bundle-create)
    run_mvn "distribution" "repository:bundle-create" "-Dsign=true"
    ;;
  *)
    if [ -n "$1" ]; then
      echo "Invalid command"
    fi
    echo "USAGE: `basename $0` [--with-jdk8] clean|javadoc|package|verify|install|versions-set|versions-display-dependency|versions-display-plugin|deploy|bundle-create"
esac
