#!/bin/bash

# Build all container images
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$DIR/.." && pwd)"

echo "Building all container images..."
echo

"$DIR/build" flink "$@"
"$DIR/build" relay "$@"
"$DIR/build" ingestor "$@"
"$DIR/build" web "$@"

# Build lifecycle-sidecar (Go binary, no protobuf sync needed)
echo "Building lifecycle-sidecar..."
cd "$ROOT_DIR/lifecycle-sidecar"

# Determine tag
if [ "$1" == "dev" ]; then
  TAG="dev$(date +%Y%m%d%H%M%S)"
else
  # Check for uncommitted changes
  DIRTY="$(git status | grep 'Changes ' || true)"
  if [ "$DIRTY" != "" ]; then
    echo "lifecycle-sidecar has uncommitted changes."
    echo "Use '$0 dev' to build a development-tagged version instead."
    exit 1
  fi
  TAG="$(git log --oneline | head -1 | cut -d ' ' -f 1)"
fi

REMOTE=${REMOTE:-ghcr.io/dexorder}

docker build -t lifecycle-sidecar:latest -t lifecycle-sidecar:$TAG .
docker tag lifecycle-sidecar:$TAG $REMOTE/lifecycle-sidecar:$TAG
docker tag $REMOTE/lifecycle-sidecar:$TAG $REMOTE/lifecycle-sidecar:latest

echo "$(date)" built $REMOTE/lifecycle-sidecar:$TAG

echo
echo "All images built successfully!"
