#!/usr/bin/env bash
# Build and smoke-test the Capacity Planner image without publishing
# anything: non-root user + exact entrypoint assertions, then a read-only,
# no-network --help run that must exit 0. The temporary tag is unique per
# shell PID and always removed (also on failure).
#
# Run from the module root (internal/capacity-planner).
set -euo pipefail

CONTAINER_TOOL=${CONTAINER_TOOL:-docker}
VERSION=${VERSION:-v0.0.0}
COMMIT=${COMMIT:-unknown}
TAG="capacity-planner:verify-$$"

cleanup() {
  "$CONTAINER_TOOL" rmi "$TAG" >/dev/null 2>&1 || true
}
trap cleanup EXIT

"$CONTAINER_TOOL" build -t "$TAG" \
  --build-arg GIT_VERSION="$VERSION" \
  --build-arg GIT_COMMIT="$COMMIT" \
  -f Dockerfile .

USER_CFG=$("$CONTAINER_TOOL" image inspect --format '{{.Config.User}}' "$TAG")
if [ "$USER_CFG" != "65532:65532" ]; then
  echo "test/container: unexpected image user '$USER_CFG' (want 65532:65532)" >&2
  exit 1
fi

EP=$("$CONTAINER_TOOL" image inspect --format '{{json .Config.Entrypoint}}' "$TAG")
if [ "$EP" != '["/capacity-planner"]' ]; then
  echo "test/container: unexpected entrypoint $EP (want [\"/capacity-planner\"])" >&2
  exit 1
fi

# Smoke: non-root (belt and braces), read-only rootfs, no network.
"$CONTAINER_TOOL" run --rm --read-only --network=none --user 65532:65532 "$TAG" --help >/dev/null

echo "test/container: OK (build, user/entrypoint assertions, --help smoke)"
