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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

require() {
  local name="$1"
  if [[ -z "${!name:-}" ]]; then
    echo "Missing env: ${name}" >&2
    exit 2
  fi
}

require ACR_REGISTRY
require ACR_NAMESPACE

image_repo="${IMAGE_REPO:-digital-archive-frontend}"
image_tag="${IMAGE_TAG:-}"

if [[ -z "$image_tag" ]]; then
  if command -v git >/dev/null 2>&1; then
    image_tag="$(git -C "$script_dir" rev-parse --short HEAD 2>/dev/null || true)"
  fi
fi

if [[ -z "$image_tag" ]]; then
  image_tag="$(date +%Y%m%d%H%M%S)"
fi

image_ref="${ACR_REGISTRY}/${ACR_NAMESPACE}/${image_repo}:${image_tag}"

if [[ -n "${ACR_USERNAME:-}" && -n "${ACR_PASSWORD:-}" ]]; then
  printf '%s' "$ACR_PASSWORD" | docker login "$ACR_REGISTRY" -u "$ACR_USERNAME" --password-stdin
fi

build_args=()
if [[ -n "${PKG_MANAGER:-}" ]]; then
  build_args+=(--build-arg "PKG_MANAGER=${PKG_MANAGER}")
fi
if [[ -n "${NPM_REGISTRY:-}" ]]; then
  build_args+=(--build-arg "NPM_REGISTRY=${NPM_REGISTRY}")
fi

docker build \
  -f "$script_dir/Dockerfile" \
  -t "$image_ref" \
  "${build_args[@]}" \
  "$script_dir"

docker push "$image_ref"

echo "Pushed: $image_ref"
echo "WEB_IMAGE=$image_ref"
