#!/bin/bash
# Aria Sandbox Run (V5 Sprint 5)
# Führt Bash-Commands in isolierten Docker-Container aus.
# Pattern: Aria ruft das freiwillig auf für riskante Operations
# (curl|bash, npm install, fremde Skripte).
#
# Aufruf:
#   aria-sandbox-run.sh "<command>"          # echo + run
#   aria-sandbox-run.sh -i image "<command>" # custom image (default: alpine)
#   aria-sandbox-run.sh --no-net "<command>" # network disabled
#   aria-sandbox-run.sh --rw-mount /tmp/x:/tmp/x "<command>"  # writable mount
#
# Default: Alpine Linux, no network, readonly /tmp mount, 60s timeout.
# Container wird nach run automatisch removed (--rm).
#
# Inspiriert von OpenClaw sandbox.mode=non-main + Hermes terminal-environments docker.

set -e

IMAGE="alpine:latest"
NETWORK="--network=none"
TIMEOUT_SEC=60
EXTRA_MOUNTS=""

# Args parse
while [ $# -gt 0 ]; do
    case "$1" in
        -i|--image) IMAGE="$2"; shift 2 ;;
        --no-net) NETWORK="--network=none"; shift ;;
        --net) NETWORK=""; shift ;;
        --timeout) TIMEOUT_SEC="$2"; shift 2 ;;
        --rw-mount)
            EXTRA_MOUNTS="$EXTRA_MOUNTS -v $2"
            shift 2
            ;;
        --) shift; break ;;
        -*) echo "Unknown arg: $1" >&2; exit 1 ;;
        *) break ;;
    esac
done

CMD="${*}"
if [ -z "$CMD" ]; then
    cat << 'EOF'
Usage: aria-sandbox-run.sh [opts] "<command>"

Options:
  -i, --image IMG     Container-Image (default: alpine:latest)
      --no-net        Network disabled (default)
      --net           Network enabled (für npm install, curl, etc.)
      --timeout SEC   Timeout in seconds (default: 60)
      --rw-mount X:Y  Writable Mount (Host:Container)

Examples:
  aria-sandbox-run.sh "ls -la /"
  aria-sandbox-run.sh --net -i node:24-alpine "npm install ruflo --dry-run"
  aria-sandbox-run.sh --rw-mount /tmp/sandbox:/work "echo hi > /work/test.txt"

Pattern: Aria ruft das auf für riskante Operations bevor sie auf den Host gehen.
EOF
    exit 0
fi

# Pre-flight: Docker available?
if ! command -v docker >/dev/null 2>&1; then
    echo "ERROR: docker not installed. Install with: apt install docker.io" >&2
    exit 1
fi

if ! docker info >/dev/null 2>&1; then
    echo "ERROR: docker daemon not running or no permissions." >&2
    exit 1
fi

echo "[sandbox-run] image=$IMAGE network=${NETWORK:-bridge} timeout=${TIMEOUT_SEC}s"
echo "[sandbox-run] cmd: $CMD"
echo "---"

# Run with: --rm (auto-remove), --read-only filesystem,
# --tmpfs /tmp (writable tmp), --user 1000 (no-root in container)
# Falls user braucht root in container für package installs: --user-passthrough
exec timeout "$TIMEOUT_SEC" docker run --rm \
    --read-only \
    --tmpfs /tmp:size=64m \
    --tmpfs /home/sandbox:size=16m \
    --user 1000:1000 \
    -e HOME=/home/sandbox \
    -w /home/sandbox \
    $NETWORK \
    $EXTRA_MOUNTS \
    "$IMAGE" \
    sh -c "$CMD"
