#!/usr/bin/env bash
# Mode A setup for macOS 26 / Apple Silicon: build the AIMem image, run it,
# wait for the FUSE workspace, then enter /workspace or run the supplied agent.
#
# Usage:
#   AIMEM_BUCKET=my-project \
#   AIMEM_ENDPOINT_URL=https://aistor.example.com:9000 \
#   AIMEM_ACCESS_KEY=... AIMEM_SECRET_KEY=... \
#   bash examples/apple-container/run.sh -- bash
#
# AIMEM_BUCKET must be a Memory Bucket on a paid-tier AIStor; create
# it once with `aimem create <bucket> --endpoint-url ...`. aimem mounts
# only Memory Buckets, and the mount gate requires signing creds via AIMEM_ACCESS_KEY
# / AIMEM_SECRET_KEY (the default/AWS credential chain is rejected).
set -euo pipefail

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

if [ "${1:-}" = "--" ]; then shift; fi

: "${AIMEM_BUCKET:?set AIMEM_BUCKET}"
: "${AIMEM_ENDPOINT_URL:?set AIMEM_ENDPOINT_URL}"
: "${AIMEM_ACCESS_KEY:?set AIMEM_ACCESS_KEY}"
: "${AIMEM_SECRET_KEY:?set AIMEM_SECRET_KEY}"

NAME="${AIMEM_CONTAINER_NAME:-aimem-ws}"
IMAGE="${AIMEM_IMAGE:-aimem-mac-base}"
MOUNTPOINT="${AIMEM_MOUNTPOINT:-/workspace}"
LOCAL_DIR="${AIMEM_LOCAL:-/staging}"
STAGING_VOLUME="${AIMEM_STAGING_VOLUME:-aimem-staging}"

fail() { printf 'FAIL: %s\n' "$1" >&2; exit 1; }
note() { printf '== %s\n' "$1"; }

add_env_if_set() {
    local name="$1"
    if [ -n "${!name:-}" ]; then run_args+=(-e "$name"); fi
}

command -v container >/dev/null 2>&1 || fail "Apple container CLI not found on PATH"

note "start Apple container system"
container system start >/dev/null || fail "container system start failed"

note "build AIMem image"
build_args=(--arch arm64 -t "$IMAGE" -f "$HERE/Containerfile")
if [ -n "${AIMEM_VERSION:-}" ]; then build_args+=(--build-arg "AIMEM_VERSION=$AIMEM_VERSION"); fi
if [ -n "${AIMEM_DL_BASE:-}" ]; then build_args+=(--build-arg "AIMEM_DL_BASE=$AIMEM_DL_BASE"); fi
container build "${build_args[@]}" "$HERE" || fail "image build failed"

note "create persistent staging volume"
container volume create "$STAGING_VOLUME" >/dev/null 2>&1 || true

note "replace existing $NAME container if present"
container stop "$NAME" >/dev/null 2>&1 || true
container rm "$NAME" >/dev/null 2>&1 || true

note "run AIMem mount container"
run_args=(-d --name "$NAME" --cap-add SYS_ADMIN
    -v "$STAGING_VOLUME:$LOCAL_DIR"
    -e "AIMEM_BUCKET=$AIMEM_BUCKET"
    -e "AIMEM_ENDPOINT_URL=$AIMEM_ENDPOINT_URL"
    -e "AIMEM_MOUNTPOINT=$MOUNTPOINT"
    -e "AIMEM_LOCAL=$LOCAL_DIR"
    -e AIMEM_ACCESS_KEY
    -e AIMEM_SECRET_KEY)
add_env_if_set AIMEM_SESSION_TOKEN
add_env_if_set AIMEM_REGION
add_env_if_set AIMEM_PREFIX
add_env_if_set AIMEM_AGENT
add_env_if_set AIMEM_ALLOW_OTHER
container run "${run_args[@]}" "$IMAGE" >/dev/null || fail "container run failed"

note "wait for AIMem mount at $MOUNTPOINT"
for _ in $(seq 1 60); do
    if container exec "$NAME" mountpoint -q "$MOUNTPOINT" 2>/dev/null; then
        break
    fi
    sleep 1
done
container exec "$NAME" mountpoint -q "$MOUNTPOINT" || {
    container logs "$NAME" 2>&1 | tail -40
    fail "$MOUNTPOINT did not mount"
}

if [ "$#" -eq 0 ]; then set -- bash; fi

printf '\nAIMem is mounted in container %s at %s.\n' "$NAME" "$MOUNTPOINT"
printf 'Running command in the workspace: %s\n\n' "$*"

tty_args=()
if [ -t 0 ] && [ -t 1 ]; then tty_args=(-ti); fi
# ${tty_args[@]+"${tty_args[@]}"} (not "${tty_args[@]}") because macOS ships
# bash 3.2 as /bin/bash, which treats expanding an empty array under `set -u`
# as an unbound-variable error; bash 4.4+ doesn't. This form is safe on both.
container exec ${tty_args[@]+"${tty_args[@]}"} "$NAME" bash -lc 'cd "$1" && shift && exec "$@"' bash "$MOUNTPOINT" "$@"
