#!/usr/bin/env bash
# filepath: e:\infoalloggi-monorepo\build_and_push_ghcr.sh
set -euo pipefail

# Build and push multiple Docker images to a registry (GHCR or self-hosted)
# Usage:
#   ./build_and_push_ghcr.sh [TAG]
# Environment variables (defaults shown):
#   TAG (arg or env, default: latest)
#   IMAGE_REGISTRY (default: ghcr.io)
#   OWNER (default: marcopedone)
#   SERVICES (space-separated list, default: backend web db)
#   USERNAME (optional): registry username for docker login
#   TOKEN (optional): registry password/token for docker login
#
# The script expects subfolders for services when building from source:
#  - db -> ./apps/db
#  - backend -> ./apps/backend
#  - web -> ./apps/infoalloggi

: "${TAG:?TAG is required}"
: "${IMAGE_REGISTRY:?IMAGE_REGISTRY is required}"
: "${PREFIX:?PREFIX is required}"
: "${OWNER:?OWNER is required}"
: "${USERNAME:?USERNAME is required}"
: "${TOKEN:?TOKEN is required}"
: "${ENV_FILE:?ENV_FILE is required}"

# Load environment variables from the env file
if [[ -f "${ENV_FILE}" ]]; then
  echo "Loading environment from ${ENV_FILE}"
  set -a # automatically export all variables
  # shellcheck source=/dev/null
  source "${ENV_FILE}"
  set +a
else
  echo "Error: ENV_FILE ${ENV_FILE} not found"
  exit 1
fi

# Optional login
if [[ -n "${USERNAME}" && -n "${TOKEN}" ]]; then
  echo "Logging into ${IMAGE_REGISTRY} as ${USERNAME}..."
  echo "${TOKEN}" | docker login "${IMAGE_REGISTRY}" -u "${USERNAME}" --password-stdin
else
  echo "No credentials provided; assuming you're already logged into ${IMAGE_REGISTRY} or using a credential helper."
fi

# Get last git commit info (once for all images)
GIT_COMMIT_ID=$(git rev-parse --short HEAD)
GIT_COMMIT_MSG=$(git log -1 --pretty=%B | tr -d '\n')
DESCRIPTION="Commit: ${GIT_COMMIT_ID} - ${GIT_COMMIT_MSG}"

# Array to store built images
declare -a BUILT_IMAGES=()

echo "================================"
echo "PHASE 1: Building all images"
echo "================================"

IMAGE="${IMAGE_REGISTRY}/${OWNER}/${PREFIX}-web:${TAG}"
echo ""
echo "Building ${PREFIX}-web -> ${IMAGE} (context: ./apps/infoalloggi)"

docker build \
  --build-arg BASE_URL="${BASE_URL}" \
  --build-arg NEXT_PUBLIC_BASE_URL="${BASE_URL}" \
  --build-arg NEXT_PUBLIC_STRIPE_PUBLIC_KEY="${NEXT_PUBLIC_STRIPE_PUBLIC_KEY}" \
  -t "${IMAGE}" \
  --label "org.opencontainers.image.description=${DESCRIPTION}" \
  -f "./apps/infoalloggi/Dockerfile" \
  "./apps/infoalloggi"

BUILT_IMAGES+=("${IMAGE}")
echo "✓ Built ${IMAGE}"

IMAGE="${IMAGE_REGISTRY}/${OWNER}/${PREFIX}-backend:${TAG}"
echo ""
echo "Building ${PREFIX}-backend -> ${IMAGE} (context: ./apps/backend)"

docker build \
  -t "${IMAGE}" \
  --label "org.opencontainers.image.description=${DESCRIPTION}" \
  -f "./apps/backend/Dockerfile" \
  "./apps/backend"

BUILT_IMAGES+=("${IMAGE}")
echo "✓ Built ${IMAGE}"

echo ""
echo "================================"
echo "PHASE 2: Pushing all images"
echo "================================"

for IMAGE in "${BUILT_IMAGES[@]}"; do
  echo ""
  echo "Pushing ${IMAGE}"
  docker push "${IMAGE}"
  echo "✓ Pushed ${IMAGE}"
done

echo ""
echo "================================"
echo "All done!"
echo "Built and pushed ${#BUILT_IMAGES[@]} images with tag ${TAG}"
echo "Images:"
for IMAGE in "${BUILT_IMAGES[@]}"; do
  echo "  - ${IMAGE}"
done
echo "================================"
