#!/usr/bin/env bash
# Build the AIMem E2B template.
#
# By default the image fetches the released `aimem` + `aimem-fusermount`
# binaries from the public CDN (https://dl.min.io/aistor/aimem) — nothing
# to stage. To build against local binaries instead, drop Linux/amd64
# `aimem` and `aimem-fusermount` into ./bin/; e2b.Dockerfile detects and
# uses them automatically (this is the offline / CI path).
#
# Env:
#   TEMPLATE_NAME  override the published template name [default: aimem-workspace]
# Pass-through args: anything after this script's args goes to
# `e2b template create`. To pin the CDN release, pass a build arg through
# (CLI permitting): ./build.sh --build-arg AIMEM_VERSION=RELEASE.<date>

set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd "${SCRIPT_DIR}"

TEMPLATE_NAME="${TEMPLATE_NAME:-aimem-workspace}"

if [ -n "${E2B_BIN:-}" ]; then
    E2B_CMD=("${E2B_BIN}")
elif command -v e2b >/dev/null 2>&1; then
    E2B_CMD=(e2b)
elif command -v npx >/dev/null 2>&1; then
    E2B_CMD=(npx -y @e2b/cli@latest)
else
    echo "error: install the E2B CLI or npm/npx, then rerun $0" >&2
    exit 127
fi

# No --cmd / --ready-cmd: those run in a lifecycle phase that doesn't see
# the envs passed to Sandbox.create(), so the mount can't happen there.
# usage.ts launches aimem-mount via sb.commands.run after creation.
exec "${E2B_CMD[@]}" template create "${TEMPLATE_NAME}" \
    -d e2b.Dockerfile \
    --cpu-count 2 \
    --memory-mb 2048 \
    "$@"
