#!/usr/bin/env bash
#
# build.sh — Build the El landing Docker image.
#
# Pipeline:
#   1. Stage the foundation El runtime into ./runtime/ (Docker needs it
#      inside the build context — symlinks don't cross context boundaries
#      cleanly on every Docker version).
#   2. Compile server.el to server.c using the canonical elc at
#      foundation/el/dist/platform/elc.
#   3. docker buildx build for linux/amd64 (Cloud Run runs amd64 images).
#
# Both the staged ./runtime/ and the generated ./server.c are git-ignored
# — they're build artifacts. server.el and the Dockerfile are the source
# of truth.
#
# Usage:
#   ./build.sh           — build neuron-landing:dev locally
#   ./build.sh --tag X   — build with a specific tag
#   ./build.sh --push    — also push to GCP Artifact Registry (won't
#                          activate; Cloud Run service flip is manual)

set -euo pipefail

cd "$(dirname "$0")"

LANDING_DIR=$(pwd)
EL_HOME="${EL_HOME:-${LANDING_DIR}/../../foundation/el}"
ELC="${EL_HOME}/dist/platform/elc"
RUNTIME_SRC="${EL_HOME}/el-compiler/runtime"

TAG="dev"
PUSH=0
while [ $# -gt 0 ]; do
    case "$1" in
        --tag) TAG="$2"; shift 2 ;;
        --push) PUSH=1; shift ;;
        *) echo "unknown flag: $1" >&2; exit 1 ;;
    esac
done

echo "==> Staging El runtime from ${RUNTIME_SRC}"
mkdir -p runtime
cp "${RUNTIME_SRC}/el_runtime.c" runtime/
cp "${RUNTIME_SRC}/el_runtime.h" runtime/

echo "==> Compiling server.el → server.c via ${ELC}"
"${ELC}" server.el > server.c

echo "==> Building Docker image neuron-landing:${TAG} for linux/amd64"
docker buildx build --platform linux/amd64 --load -t "neuron-landing:${TAG}" .

if [ "${PUSH}" = "1" ]; then
    REGISTRY="us-central1-docker.pkg.dev/neuron-785695/neuron-marketing"
    REMOTE_TAG="${REGISTRY}/marketing:${TAG}"
    echo "==> Tagging and pushing ${REMOTE_TAG}"
    docker tag "neuron-landing:${TAG}" "${REMOTE_TAG}"
    docker push "${REMOTE_TAG}"
    echo "(image pushed; Cloud Run service flip is a separate step)"
fi

echo "==> Done. Run with:"
echo "    docker run --rm -p 8080:8080 neuron-landing:${TAG}"
