#!/usr/bin/env bash
# Mode B setup on macOS 26 / Apple Silicon: build the full image, run it,
# mount the workspace on the Mac host over SMB, and leave it mounted.
#
# Usage:
#   AIMEM_BUCKET=my-project \
#   AIMEM_ENDPOINT_URL=https://aistor.example.com:9000 \
#   AIMEM_ACCESS_KEY=... AIMEM_SECRET_KEY=... \
#   bash examples/apple-container/usage.sh
#
# 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)"

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

: "${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}"
command -v container >/dev/null 2>&1 || fail "Apple container CLI not found on PATH"
command -v uuidgen >/dev/null 2>&1 || fail "uuidgen not found on PATH"

NAME="${AIMEM_CONTAINER_NAME:-aimem-ws}"
IMAGE="${AIMEM_IMAGE:-aimem-mac-full}"
STAGING_VOLUME="${AIMEM_STAGING_VOLUME:-aimem-staging}"
SMB_USER="${AIMEM_SMB_USER:-agent}"
GENERATED_PASSWORD=0
if [ -z "${AIMEM_SMB_PASSWORD:-}" ]; then
    AIMEM_SMB_PASSWORD="$(uuidgen | tr -d '-' | cut -c 1-20)"
    GENERATED_PASSWORD=1
fi
# Mount to a user-writable dir (creating /Volumes/* needs sudo). Finder users
# can instead `open smb://<ip>/workspace` to auto-mount under /Volumes.
MNT="${AIMEM_MNT:-$HOME/aimem-workspace}"
SUCCESS=0

cleanup() {
    if [ "$SUCCESS" -eq 0 ]; then
        umount "$MNT" 2>/dev/null || true
        container stop "$NAME" >/dev/null 2>&1 || true
        container rm "$NAME" >/dev/null 2>&1 || true
    fi
}
trap cleanup EXIT

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

note "build full image"
build_args=(--arch arm64 -t "$IMAGE" -f "$HERE/Containerfile.full")
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 "build failed"

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

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

note "run full image (aimem + smbd)"
run_args=(-d --name "$NAME" --cap-add SYS_ADMIN
    -v "$STAGING_VOLUME:/staging"
    -e AIMEM_BUCKET="$AIMEM_BUCKET" -e AIMEM_ENDPOINT_URL="$AIMEM_ENDPOINT_URL" \
    -e AIMEM_ACCESS_KEY -e AIMEM_SECRET_KEY \
    -e AIMEM_SMB_PASSWORD="$AIMEM_SMB_PASSWORD" -e AIMEM_SMB_USER="$SMB_USER")
if [ -n "${AIMEM_SESSION_TOKEN:-}" ]; then run_args+=(-e AIMEM_SESSION_TOKEN); fi
if [ -n "${AIMEM_REGION:-}" ]; then run_args+=(-e AIMEM_REGION); fi
if [ -n "${AIMEM_PREFIX:-}" ]; then run_args+=(-e AIMEM_PREFIX); fi
if [ -n "${AIMEM_AGENT:-}" ]; then run_args+=(-e AIMEM_AGENT); fi
container run "${run_args[@]}" "$IMAGE" >/dev/null || fail "run failed"

note "wait for mount + smbd"
for _ in $(seq 1 60); do
    container exec "$NAME" mountpoint -q /workspace 2>/dev/null && break
    sleep 1
done
container exec "$NAME" mountpoint -q /workspace || { container logs "$NAME" 2>&1 | tail -40; fail "workspace not mounted"; }

note "xattr probe (vfs_fruit streams_xattr stores ADS as xattrs on the FUSE layer)"
if container exec "$NAME" sh -c 'touch /workspace/.xattr-probe && setfattr -n user.test -v 1 /workspace/.xattr-probe && getfattr -d /workspace/.xattr-probe && rm -f /workspace/.xattr-probe' 2>/dev/null; then
    printf '   xattrs OK — streams_xattr supported\n'
else
    printf '   WARNING: xattrs unsupported on the FUSE layer; drop streams_xattr / set fruit:metadata=netatalk in smb.conf\n'
fi

note "resolve container IP (container ls --format only accepts json/table/etc.)"
IP="$(container inspect "$NAME" 2>/dev/null | grep -oE '"ipv4Address"[^0-9]*[0-9.]+' | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | head -1)"
[ -n "$IP" ] || fail "could not resolve container IP (run: container ls)"
printf '   container IP: %s\n' "$IP"

note "TCP/445 reachable from host?"
nc -vz -G 5 "$IP" 445 || fail "445 unreachable — try the container DNS-domain flow or check subnet collision (see README)"

note "mount over SMB on the host"
mkdir -p "$MNT"
mount_smbfs "//$SMB_USER:$AIMEM_SMB_PASSWORD@$IP/workspace" "$MNT" \
    || fail "mount_smbfs failed (check Local Network Privacy / credentials)"
ls -la "$MNT" || fail "cannot list mounted workspace"

note "writable workspace smoke over SMB"
SMOKE_DIR="$MNT/.aimem-smoke/apple-container-$(date +%s)-$$"
mkdir -p "$SMOKE_DIR" || fail "cannot create smoke dir"
printf 'edit from mac\n' > "$SMOKE_DIR/host-edit.txt" || fail "write over SMB failed"
grep -qx 'edit from mac' "$SMOKE_DIR/host-edit.txt" || fail "read over SMB failed"
rm -rf "$SMOKE_DIR"
rmdir "$MNT/.aimem-smoke" 2>/dev/null || true

SUCCESS=1
printf '\nMODE B READY: workspace is mounted on the Mac at %s and writable over SMB.\n' "$MNT"
if [ "$GENERATED_PASSWORD" -eq 1 ]; then
    printf 'Generated SMB password for this container: %s\n' "$AIMEM_SMB_PASSWORD"
fi
printf 'Stop later with: umount %q; container stop %q; container rm %q\n' "$MNT" "$NAME" "$NAME"
