#!/bin/bash
# Build CI images locally using the unified Dockerfile.service-ci
# For CI pipeline builds, see .woodpecker/build-ci-images.yml
set -euo pipefail

cd "$(dirname "$0")/.."

REGISTRY="${REGISTRY:-registry.niovi.voyage}"
TAG="${TAG:-latest}"

echo "=== Building CI images ==="
echo "Registry: $REGISTRY"
echo "Tag: $TAG"

# Build ponder-ci
echo ""
echo "=== Building ponder-ci ==="
docker build \
  -f docker/Dockerfile.service-ci \
  --build-arg SERVICE_DIR=services/ponder \
  --build-arg SERVICE_PORT=42069 \
  --build-arg ENTRYPOINT_SCRIPT=containers/ponder-entrypoint.sh \
  --build-arg HEALTHCHECK_RETRIES=12 \
  --build-arg HEALTHCHECK_START=20s \
  -t "$REGISTRY/harb/ponder-ci:$TAG" \
  .

# Build webapp-ci
echo ""
echo "=== Building webapp-ci ==="
docker build \
  -f docker/Dockerfile.service-ci \
  --build-arg SERVICE_DIR=web-app \
  --build-arg SERVICE_PORT=5173 \
  --build-arg HEALTHCHECK_PATH=/app/ \
  --build-arg HEALTHCHECK_RETRIES=84 \
  --build-arg HEALTHCHECK_START=15s \
  --build-arg ENTRYPOINT_SCRIPT=containers/webapp-entrypoint.sh \
  --build-arg NODE_ENV=development \
  --build-arg NEEDS_SYMLINKS=true \
  -t "$REGISTRY/harb/webapp-ci:$TAG" \
  .

# Build landing-ci
echo ""
echo "=== Building landing-ci ==="
docker build \
  -f docker/Dockerfile.service-ci \
  --build-arg SERVICE_DIR=landing \
  --build-arg SERVICE_PORT=5174 \
  --build-arg ENTRYPOINT_SCRIPT=containers/landing-ci-entrypoint.sh \
  --build-arg NODE_ENV=development \
  --build-arg HEALTHCHECK_RETRIES=6 \
  --build-arg HEALTHCHECK_START=10s \
  -t "$REGISTRY/harb/landing-ci:$TAG" \
  .

# Build txnbot-ci
echo ""
echo "=== Building txnbot-ci ==="
docker build \
  -f docker/Dockerfile.service-ci \
  --build-arg SERVICE_DIR=services/txnBot \
  --build-arg SERVICE_PORT=43069 \
  --build-arg HEALTHCHECK_PATH=/status \
  --build-arg HEALTHCHECK_RETRIES=4 \
  --build-arg HEALTHCHECK_START=10s \
  --build-arg ENTRYPOINT_SCRIPT=containers/txnbot-entrypoint.sh \
  --build-arg NPM_INSTALL_CMD=install \
  -t "$REGISTRY/harb/txnbot-ci:$TAG" \
  .

echo ""
echo "=== All images built ==="
echo ""

# Push if requested
if [[ "${PUSH:-false}" == "true" ]]; then
  echo "=== Pushing images to registry ==="
  docker push "$REGISTRY/harb/ponder-ci:$TAG"
  docker push "$REGISTRY/harb/webapp-ci:$TAG"
  docker push "$REGISTRY/harb/landing-ci:$TAG"
  docker push "$REGISTRY/harb/txnbot-ci:$TAG"
  echo "=== All images pushed ==="
else
  echo "To push images, run: PUSH=true $0"
fi
