#!/usr/bin/env bash

# Run meka in an archlinux:latest container with the host's meka binary
# bind-mounted in. Requires meka installed and configured on the host.

set -euo pipefail

for dir in "$HOME/.config/meka" "$HOME/.local/share/meka"; do
    if [[ ! -d "$dir" ]]; then
        echo "$(basename "$0"): missing $dir; setup meka on the host first" >&2
        exit 1
    fi
done

# Resolve the host meka binary from PATH (cargo, distro package, etc.).
meka_bin="$(command -v meka || true)"
if [[ -z "$meka_bin" || ! -x "$meka_bin" ]]; then
    echo "$(basename "$0"): meka not found in PATH; install meka on the host first" >&2
    exit 1
fi

# Pick a container runtime: prefer podman (rootless by default), fall back to docker.
if command -v podman >/dev/null 2>&1; then
    runtime="podman"
elif command -v docker >/dev/null 2>&1; then
    runtime="docker"
else
    echo "$(basename "$0"): neither podman nor docker found in PATH" >&2
    exit 1
fi

# Probe the runtime once to determine whether sudo is needed.
sudo_prefix=()
if ! "$runtime" info >/dev/null 2>&1; then
    if ! command -v sudo >/dev/null 2>&1; then
        echo "$(basename "$0"): $runtime is not usable and sudo is not available" >&2
        exit 1
    fi
    sudo_prefix=(sudo)
fi

# Override instructions for the containerized environment
mekabox_instructions='You are running inside an isolated mekabox container with full root privileges.
You may freely install system packages (pacman -S, apt install, etc.), language runtimes, and
developer tooling as needed for the task. Container changes do not persist between invocations
except in mounted volumes.

Limit all changes to within this container; do not attempt to modify the host system or rely on
changes persisting outside mounted volumes.

Prefer Exa Search (`mcp__exa__web_search_exa` and `mcp__exa__web_fetch_exa`) over the built-in
`web_search` tool for searches, when available.'

# `MEKA_SANDBOX_BACKEND=landlock` pins the read-mode sandbox to Landlock inside the container.
# Bubblewrap rarely works in a nested container, and the image has no host config to pin it in
# (the host config is mounted read-only), so this also silences the auto-resolve warning.
#
# `--entrypoint` must precede the image; archlinux:latest has none.
exec "${sudo_prefix[@]}" "$runtime" run --rm -it \
    --entrypoint /usr/local/bin/meka \
    -v "$meka_bin:/usr/local/bin/meka:ro" \
    -v "$HOME/.config/meka:/root/.config/meka:ro" \
    -v "$HOME/.local/share/meka:/root/.local/share/meka:rw" \
    -e MEKA_PERMISSION=write \
    -e MEKA_INSTRUCTIONS="$mekabox_instructions" \
    -e MEKA_SANDBOX_BACKEND=landlock \
    archlinux:latest \
    "$@"
