#!/bin/bash

DIRNAME="$(dirname "$0")"
if [ -f "${DIRNAME}/align.properties" ]; then
  . "${DIRNAME}/align.properties"
fi

BASE_MANIFEST_GAV="org.jboss.eap.channels:eap-8.0"
XP5_MANIFEST_GAV="org.jboss.eap.channels:eap-xp-5.0"
TARGET_DIR="./target"
VERBOSE=false

usage() {
  echo "Usage: align-dependencies-xp5.sh [-v] [path/to/base-manifest.yaml path/to/xp5-manifest.yaml]"
  echo
  echo "If no manifest paths are given, the manifests will be downloaded from a Maven repository."
  echo "The latest available versions of the base (EAP8) and XP5 manifests will be used in this case."
}

# Parse options
while getopts ":v" opt; do
  case ${opt} in
    v )
      VERBOSE=true
      ;;
    \? )
      usage
      exit 1
      ;;
  esac
done
shift $((OPTIND -1))

# Maven invocation with verbosity control
mvn_exec() {
  if [ "$VERBOSE" = true ]; then
    echo mvn "$@"
    mvn "$@"
  else
    mvn "$@" > /dev/null
  fi
}

# Check input parameters
if [ "$#" -eq 0 ]; then
  echo "Getting the latest available versions of the manifests."

  mkdir -p "$TARGET_DIR"

  # Download and copy manifests
  mvn_exec dependency:get -Dartifact=${BASE_MANIFEST_GAV}:LATEST:yaml:manifest \
    || { echo "Failed to update local Maven cache for EAP8."; exit 1; }
  mvn_exec dependency:copy -Dartifact=${BASE_MANIFEST_GAV}:LATEST:yaml:manifest -DoutputDirectory="$TARGET_DIR" -Dmdep.stripVersion=true -Dmdep.overWriteReleases=true \
    || { echo "Failed to copy base manifest."; exit 1; }
  mvn_exec dependency:get -Dartifact=${XP5_MANIFEST_GAV}:LATEST:yaml:manifest \
    || { echo "Failed to update local Maven cache for XP5."; exit 1; }
  mvn_exec dependency:copy -Dartifact=${XP5_MANIFEST_GAV}:LATEST:yaml:manifest -DoutputDirectory="$TARGET_DIR" -Dmdep.stripVersion=true -Dmdep.overWriteReleases=true \
    || { echo "Failed to copy XP5 manifest."; exit 1; }

  BASE_MANIFEST="$TARGET_DIR/eap-8.0-manifest.yaml"
  XP5_MANIFEST="$TARGET_DIR/eap-xp-5.0-manifest.yaml"
elif [ "$#" -eq 2 ]; then
  if [ -f "$1" ] && [ -f "$2" ]; then
    echo "Using provided manifest files."
    BASE_MANIFEST="$1"
    XP5_MANIFEST="$2"
  else
    echo "Error: One or both manifest files not found."
    usage
    exit 1
  fi
else
  echo "Error: Illegal number of parameters"
  echo
  usage
  exit 1
fi

if [ ! -f "$BASE_MANIFEST" ]; then
  echo "Error: Base manifest file not found at $BASE_MANIFEST."
  exit 1
fi

# Initialize parameters

# Manifest input parameters:
MANIFEST_PARAMS="-DmanifestFile=${BASE_MANIFEST},${XP5_MANIFEST}"

# Alignment invocation parameters:
# doNotDowngrade: If source code contains newer dependency versions than the manifest, versions will not be downgraded.
PARAMS="${MANIFEST_PARAMS} -DdoNotDowngrade=true -DignoreStreams=org.apache.maven:*,org.apache.maven.resolver:*,org.codehaus.plexus:*"

# Update the wildfly-core-parent version
echo "Upgrading the wildfly-core version."
mvn_exec org.wildfly:wildfly-channel-maven-plugin:set-property -Dproperty=version.org.wildfly.core \
  -Dstream=org.wildfly.core:wildfly-server $MANIFEST_PARAMS \
  || { echo "Failed to set the wildfly-core version."; exit 1; }

# Update the base EAP version
echo "Upgrading the base EAP version."
mvn_exec org.wildfly:wildfly-channel-maven-plugin:set-property -Dproperty=ee.maven.version \
  -Dstream=org.jboss.eap:wildfly-ee-galleon-pack $MANIFEST_PARAMS \
  || { echo "Failed to set the base EAP version."; exit 1; }

# Extract AMQP protocol version from the base EAP manifest, strip "-redhat-xxxxx" suffix, and use the resulting
# community version for the artemis-amqp-protocol test dependency.
AMQP_VERSION_LINE=$(grep -A1 'artifactId: "artemis-jakarta-server"' "${BASE_MANIFEST}" | grep 'version:')
if [ -z "$AMQP_VERSION_LINE" ]; then
  AMQP_VERSION_LINE=$(grep -A1 'artifactId: "artemis-' "${BASE_MANIFEST}" | grep 'version:')
fi
if [ -n "$AMQP_VERSION_LINE" ]; then
  AMQP_VERSION=$(echo $AMQP_VERSION_LINE | sed 's/.*version: "//;s/.redhat-[[:digit:]]\+"//')
  echo "Setting version.org.apache.activemq.artemis.amqp.protocol to \"$AMQP_VERSION\"."
  PARAMS="${PARAMS} -DoverrideProperties=version.org.apache.activemq.artemis.amqp.protocol=${AMQP_VERSION}"
else
  echo "Warning: AMQ version could not be determined; artemis-amqp-protocol version will not be set."
fi

# Upgrade remaining dependencies based on both EAP8 and XP5 manifests
echo "Upgrading dependencies."
mvn_exec org.wildfly:wildfly-channel-maven-plugin:upgrade $PARAMS \
  || { echo "Failed to upgrade dependencies."; exit 1; }

if [ -n "${ADDITIONAL_REPOS}" ]; then
  echo "Injecting additional repositories."
  mvn_exec org.wildfly:wildfly-channel-maven-plugin:inject-repositories \
    -Drepositories="${ADDITIONAL_REPOS}" || { echo "Failed to inject additional repositories."; exit 1; }
fi

echo "XP5 alignment complete."
