#!/usr/bin/env bash
# Build the naros-agent OCI image FROM an imported naros-base image (NAROS.md §4, N2).
#
#   build.sh <arch> --base IMAGE[:TAG] [--tag IMAGE:TAG] [--pool DIR]
#
# Assembles a build context (this directory + the Nucleic apt pool) so the Docker build
# context never drags in os/dist's rootfs tars, then runs a plain `docker build` for the
# requested platform. CI calls this per arch in the rootfs matrix, right after importing
# the base tar it just built; locally any imported naros-base works:
#
#   docker import os/dist/naros-base-<ver>-arm64.tar naros-base:local
#   os/images/agent/build.sh arm64 --base naros-base:local
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
OS_DIR="$(cd "$HERE/../.." && pwd)"
ARCH="${1:?usage: build.sh <arch> --base IMAGE [--tag IMAGE:TAG] [--pool DIR]}"
shift

BASE="" TAG="naros-agent:build-$ARCH" POOL="$OS_DIR/dist/pool"
while [ $# -gt 0 ]; do
  case "$1" in
    --base) BASE="$2"; shift 2 ;;
    --tag) TAG="$2"; shift 2 ;;
    --pool) POOL="$(cd "$2" && pwd)"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 2 ;;
  esac
done
[ -n "$BASE" ] || { echo "--base IMAGE required (an imported naros-base)" >&2; exit 2; }
[ -d "$POOL" ] || { echo "no apt pool at $POOL — run packages/build-all.sh first" >&2; exit 2; }

# The pool needs a flat-repo index for the in-build [trusted=yes] copy:// source; keep it
# fresh the same way build-rootfs.sh does.
if [ ! -f "$POOL/Packages" ] || [ -n "$(find "$POOL" -name '*.deb' -newer "$POOL/Packages" 2>/dev/null)" ]; then
  (cd "$POOL" && dpkg-scanpackages --multiversion . > Packages)
fi

CTX="$(mktemp -d)"
trap 'rm -rf "$CTX"' EXIT
cp -a "$HERE/Dockerfile" "$HERE/files" "$CTX/"
mkdir -p "$CTX/pool"
cp -a "$POOL/." "$CTX/pool/"

DOCKER_BUILDKIT=1 docker build \
  --platform "linux/$ARCH" \
  --build-arg "BASE=$BASE" \
  --build-arg "TARGETARCH=$ARCH" \
  -t "$TAG" \
  "$CTX"

echo "built $TAG (linux/$ARCH FROM $BASE)"
