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

# Build all project images in dependency order:
#   huskies  →  huskies-project-base  →  huskies-project-<stack> (one per stack fragment)
#
# Run this after `script/docker_rebuild` or whenever you add a new stack.
# Safe to re-run: each step re-tags the image with the latest layers.
#
# IMPORTANT (story 1231): this script is NOT part of `script/release`. The
# huskies-project-* images bake whatever `huskies` binary happened to be built
# locally the last time this ran — as of this comment that's 0.13.0, several
# releases behind the current fleet artifact. `project-rebuild` self-heals a
# sled that comes back on a stale baked binary (it re-upgrades it in place
# from the gateway's published artifact), but that costs an extra
# download+restart cycle every time. Run `script/build-project-images` after
# every `script/release` — ideally as a step in the release flow itself — so
# freshly rebuilt sleds start on a current binary instead of relying on the
# self-heal.

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

if [[ -f .env ]]; then
    set -a
    source .env
    set +a
fi

CACHE_FLAG=""
if [[ "${1:-}" == "--no-cache" ]]; then
    CACHE_FLAG="--no-cache"
fi

echo "==> Building huskies"
docker build $CACHE_FLAG -t huskies -f docker/Dockerfile .

echo "==> Building huskies-project-base"
docker build $CACHE_FLAG -t huskies-project-base -f docker/Dockerfile.base .

for fragment in docker/stacks/*/Dockerfile.fragment; do
    stack=$(basename "$(dirname "$fragment")")
    image="huskies-project-${stack}"
    echo "==> Building ${image}"
    (printf 'FROM huskies-project-base\n'; cat "$fragment") \
        | docker build $CACHE_FLAG -t "$image" -
done

echo "All project images built."
