#!/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"

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

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 -Dmaven.repo.local="${MAVEN_REPO_LOCAL}" \
      install:install-file \
      -DpomFile="${pom_file}" \
      -Dfile="${jar_file}" \
      -DgeneratePom=false
  else
    mvn -Dmaven.repo.local="${MAVEN_REPO_LOCAL}" \
      install:install-file \
      -DpomFile="${pom_file}" \
      -Dfile="${pom_file}" \
      -Dpackaging=pom \
      -DgeneratePom=false
  fi
done
