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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

normalize_arch() {
  case "$1" in
    amd64|x86_64)
      printf 'amd64\n'
      ;;
    arm64|aarch64)
      printf 'arm64\n'
      ;;
    *)
      return 1
      ;;
  esac
}

TARGET_ARCH="${TARGET_ARCH:-}"
IMAGE_TAG="${IMAGE_TAG:-}"
DOCKERFILE="${DOCKERFILE:-$REPO_ROOT/docker/ours-rp-metrics.Dockerfile}"
args=()
image_explicit=0
dockerfile_explicit=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --arch)
      TARGET_ARCH="$(normalize_arch "$2")" || {
        echo "unsupported target architecture: $2" >&2
        exit 2
      }
      args+=("$1" "$TARGET_ARCH")
      shift 2
      ;;
    --image)
      IMAGE_TAG="$2"
      image_explicit=1
      args+=("$1" "$2")
      shift 2
      ;;
    --dockerfile)
      DOCKERFILE="$2"
      dockerfile_explicit=1
      args+=("$1" "$2")
      shift 2
      ;;
    *)
      args+=("$1")
      shift
      ;;
  esac
done

if [[ -z "$TARGET_ARCH" ]]; then
  cat >&2 <<'EOF'
missing target architecture.

Usage:
  scripts/docker/build_docker_metrics_image.sh --arch amd64|arm64 [options]
EOF
  exit 2
fi

if [[ -z "$IMAGE_TAG" ]]; then
  SOURCE_COMMIT_SHORT="$(git -C "$REPO_ROOT" rev-parse --short=8 HEAD 2>/dev/null || echo unknown)"
  if [[ -n "$(git -C "$REPO_ROOT" status --short 2>/dev/null)" ]]; then
    SOURCE_COMMIT_SHORT="${SOURCE_COMMIT_SHORT}-dirty"
  fi
  IMAGE_TAG="ours-rp-metrics-${TARGET_ARCH}:${SOURCE_COMMIT_SHORT}"
fi

if [[ "$dockerfile_explicit" != "1" ]]; then
  args=(--dockerfile "$DOCKERFILE" "${args[@]}")
fi
if [[ "$image_explicit" != "1" ]]; then
  args=(--image "$IMAGE_TAG" "${args[@]}")
fi

exec "$SCRIPT_DIR/build_docker_runtime_image.sh" "${args[@]}"
