#!/usr/bin/env bash
# Build all three Go binaries for Linux/amd64 and the dashboard.
# Output goes to ./bin/ and ./dashboard/out/.
#
# Uses a golang:1.23-alpine container so we get a reproducible toolchain
# without needing Go installed locally. Cross-compile via GOOS/GOARCH +
# CGO_ENABLED=0 — produces a static binary that runs in the alpine
# containers defined in docker-compose.yml.

set -euo pipefail

cd "$(dirname "$0")/.."
REPO_ROOT="$(pwd)"

OUT="$REPO_ROOT/bin"
mkdir -p "$OUT"

GO_IMAGE="${GO_IMAGE:-golang:1.24-alpine}"

# ponytail: bind-mount a persistent gocache so module downloads + build cache
# survive across runs. Otherwise every build re-downloads the world from
# the GOPROXY — slow on a flaky office link, and uses up the proxy quota.
GOCACHE_VOL="sdp-gocache"
docker volume create "$GOCACHE_VOL" >/dev/null 2>&1 || true

echo "==> building control-plane, agent-micro, agent-gateway (linux/amd64)"
docker run --rm \
  -v "$REPO_ROOT":/src \
  -v "$OUT":/out \
  -v "$GOCACHE_VOL":/gocache \
  -w /src \
  -e CGO_ENABLED=0 \
  -e GOOS=linux \
  -e GOARCH=amd64 \
  -e GOCACHE=/gocache \
  "$GO_IMAGE" \
  sh -c '
    set -e
    # git is needed for module resolution: some deps (and go.work.sum)
    # may pull from VCS. alpine ships without it.
    apk add --no-cache git >/dev/null
    # The container runs as root and /src is bind-mounted from the host;
    # git refuses to operate on a tree it does not own ("dubious ownership").
    # We never commit inside the container — the host owns the working tree —
    # so disabling the check is safe.
    git config --global --add safe.directory /src
    # -trimpath: strip absolute paths from the binary (reproducible builds).
    # -ldflags="-s -w": drop symbol table + DWARF, smaller binary.
    go build -trimpath -ldflags="-s -w" -o /out/control-plane  ./control-plane/cmd/control-plane
    go build -trimpath -ldflags="-s -w" -o /out/agent-micro    ./agent-micro/cmd/agent-micro
    go build -trimpath -ldflags="-s -w" -o /out/agent-gateway  ./agent-gateway/cmd/agent-gateway
    # go build does not set +x; do it here while we still own the files.
    chmod +x /out/control-plane /out/agent-micro /out/agent-gateway
  '

echo
echo "==> binaries:"
ls -lh "$OUT"

# Verify the binaries are actually linux/amd64. ponytail: catches a mistake
# where someone removes the GOOS/GOARCH env and ships a darwin binary to
# the alpine container.
echo
echo "==> sanity check (file type):"
file "$OUT"/*

# ---- dashboard ----
if [[ -d "$REPO_ROOT/dashboard" ]]; then
  echo
  echo "==> building dashboard"
  if [[ ! -d "$REPO_ROOT/dashboard/node_modules" ]]; then
    (cd "$REPO_ROOT/dashboard" && npm install)
  fi
  (cd "$REPO_ROOT/dashboard" && npm run build)
  echo "dashboard built at $REPO_ROOT/dashboard/out"
fi
