#!/bin/bash
set -e

REGISTRY="${REGISTRY:-harbor.gitdata.me/gta_team}"
TAG="${TAG:-latest}"
BUILD_TARGET="${BUILD_TARGET:-x86_64-unknown-linux-gnu}"

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

# All images: (dockerfile, image-name)
declare -A ALL_IMAGES=(
    [app]="docker/app.Dockerfile"
    [gitserver]="docker/gitserver.Dockerfile"
    [email-worker]="docker/email-worker.Dockerfile"
    [git-hook]="docker/git-hook.Dockerfile"
    [migrate]="docker/migrate.Dockerfile"
    [operator]="docker/operator.Dockerfile"
)

# Filter by first argument if provided
TARGETS=("$@")
if [[ ${#TARGETS[@]} -eq 0 ]] || [[ "${TARGETS[0]}" == "all" ]]; then
    TARGETS=("${!ALL_IMAGES[@]}")
fi

for name in "${TARGETS[@]}"; do
    df="${ALL_IMAGES[$name]}"
    if [[ -z "$df" ]]; then
        echo "ERROR: unknown image '$name'"
        echo "Available: ${!ALL_IMAGES[@]}"
        exit 1
    fi
    if [[ ! -f "$df" ]]; then
        echo "ERROR: $df not found"
        exit 1
    fi
    image="${REGISTRY}/${name}:${TAG}"
    echo "==> Building $image"
    docker build \
        --build-arg BUILD_TARGET="${BUILD_TARGET}" \
        -f "$df" \
        -t "$image" \
        .
    echo "==> $image done"
    echo ""
done

echo "==> All images built:"
for name in "${TARGETS[@]}"; do
    echo "  ${REGISTRY}/${name}:${TAG}"
done
