#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
MAVEN_REPO_LOCAL="${MAVEN_REPO_LOCAL:-${HOME}/.m2/repository}"
PRIVATE_ROOT="${ROOT_DIR}/maven_private"
TMP_DIR="$(mktemp -d)"
INSTALL_POM="${TMP_DIR}/pom.xml"

trap 'rm -rf "${TMP_DIR}"' EXIT

if [ ! -d "${PRIVATE_ROOT}" ]; then
  echo "missing private maven directory: ${PRIVATE_ROOT}" >&2
  exit 1
fi

mkdir -p "${MAVEN_REPO_LOCAL}"

cat > "${INSTALL_POM}" <<'EOF'
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>local.private</groupId>
  <artifactId>install-private-maven</artifactId>
  <version>1.0.0</version>
  <packaging>pom</packaging>
</project>
EOF

# Remove cached negative lookups so Maven retries once the private artifacts are installed.
find "${MAVEN_REPO_LOCAL}/com/red/circle" -type f -name '*.lastUpdated' -delete 2>/dev/null || true

find "${PRIVATE_ROOT}" -mindepth 2 -maxdepth 2 -type d | sort | while read -r version_dir; do
  pom_file="$(find "${version_dir}" -maxdepth 1 -type f -name '*.pom' | sort | head -1)"
  if [ -z "${pom_file}" ]; then
    continue
  fi

  jar_file="$(find "${version_dir}" -maxdepth 1 -type f -name '*.jar' ! -name 'original-*' | sort | head -1 || true)"
  if [ -n "${jar_file}" ]; then
    mvn -B -f "${INSTALL_POM}" -Dmaven.repo.local="${MAVEN_REPO_LOCAL}" \
      install:install-file \
      -DpomFile="${pom_file}" \
      -Dfile="${jar_file}" \
      -DgeneratePom=false
  else
    mvn -B -f "${INSTALL_POM}" -Dmaven.repo.local="${MAVEN_REPO_LOCAL}" \
      install:install-file \
      -DpomFile="${pom_file}" \
      -Dfile="${pom_file}" \
      -Dpackaging=pom \
      -DgeneratePom=false
  fi
done
