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

ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
SERVICE_NAME="${1:-}"
IMAGE_REF="${2:-}"
SERVICE_VERSION="${SERVICE_VERSION:-${3:-dev}}"
MAVEN_REPO_LOCAL="${MAVEN_REPO_LOCAL:-${HOME}/.m2/repository}"
DOCKER_PLATFORM="${DOCKER_PLATFORM:-linux/amd64}"
SKIP_MAVEN_BUILD="${SKIP_MAVEN_BUILD:-0}"

if [ -z "${SERVICE_NAME}" ] || [ -z "${IMAGE_REF}" ]; then
  echo "usage: ci/build-service-image.sh <service> <image-ref> [service-version]" >&2
  exit 1
fi

case "${SERVICE_NAME}" in
  auth)
    MODULE_PATH="rc-auth"
    DOCKER_CONTEXT="rc-auth"
    ;;
  gateway)
    MODULE_PATH="rc-gateway"
    DOCKER_CONTEXT="rc-gateway"
    ;;
  external)
    MODULE_PATH="rc-service/rc-service-external/external-start"
    DOCKER_CONTEXT="rc-service/rc-service-external"
    ;;
  console)
    MODULE_PATH="rc-service/rc-service-console/console-start"
    DOCKER_CONTEXT="rc-service/rc-service-console"
    ;;
  other)
    MODULE_PATH="rc-service/rc-service-other/other-start"
    DOCKER_CONTEXT="rc-service/rc-service-other"
    ;;
  live)
    MODULE_PATH="rc-service/rc-service-live/live-start"
    DOCKER_CONTEXT="rc-service/rc-service-live"
    ;;
  wallet)
    MODULE_PATH="rc-service/rc-service-wallet/wallet-start"
    DOCKER_CONTEXT="rc-service/rc-service-wallet"
    ;;
  order)
    MODULE_PATH="rc-service/rc-service-order/order-start"
    DOCKER_CONTEXT="rc-service/rc-service-order"
    ;;
  *)
    echo "unsupported service: ${SERVICE_NAME}" >&2
    exit 1
    ;;
esac

cd "${ROOT_DIR}"

if [ "${SKIP_MAVEN_BUILD}" != "1" ]; then
  "${ROOT_DIR}/ci/install-private-maven.sh"

  mvn -Dmaven.repo.local="${MAVEN_REPO_LOCAL}" \
    -pl "${MODULE_PATH}" \
    -am \
    -Dmaven.test.skip=true \
    clean package
fi

docker build \
  --platform "${DOCKER_PLATFORM}" \
  -f "${DOCKER_CONTEXT}/Dockerfile" \
  --build-arg "SERVICE_VERSION=${SERVICE_VERSION}" \
  -t "${IMAGE_REF}" \
  "${DOCKER_CONTEXT}"
