#!/usr/bin/env bash
# Build and run the sandbox functional test container.
# Usage:
#   tests/sandbox/run                  Start an interactive shell (no tests)
#   tests/sandbox/run --test           Run tests, stream output, exit when done
#   tests/sandbox/run --keep-alive     Run tests, then keep container alive for exploration
#   tests/sandbox/run --ssh [PORT]     Start with SSH server + mounted git credentials
#
# Any mode can be combined with --ssh to mount ~/.ssh and ~/.gitconfig read-only:
#   tests/sandbox/run --test --ssh     Run tests with SSH git auth available
#   tests/sandbox/run --ssh            Interactive shell with SSH git auth
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"

IMAGE="equip-sandbox"
CONTAINER="equip-sandbox"
MODE="interactive"
SSH_MODE=false
SSH_PORT="2222"

for arg in "$@"; do
  case "$arg" in
    --test) MODE="test" ;;
    --keep-alive) MODE="keep-alive" ;;
    --ssh) SSH_MODE=true ;;
    [0-9]*) SSH_PORT="$arg" ;;
    *) echo "Unknown flag: $arg"; echo "Usage: $0 [--test | --keep-alive] [--ssh [PORT]]"; exit 1 ;;
  esac
done

echo "Building sandbox image..."
docker buildx build --load -f "$SCRIPT_DIR/../Dockerfile" -t "$IMAGE" "$PROJECT_DIR" || exit 1

# Remove previous container if it exists
docker rm -f "$CONTAINER" 2>/dev/null || true

# Build volume mount args for SSH/git credentials.
# ~/.ssh is mounted to a staging path — the container copies what it needs
# into /root/.ssh at startup (the image's /root/.ssh has known_hosts baked in
# and must remain writable for authorized_keys).
MOUNT_ARGS=()
if $SSH_MODE; then
  MOUNT_ARGS+=(-v "$HOME/.ssh:/tmp/host-ssh:ro")
  if [ -f "$HOME/.gitconfig" ]; then
    MOUNT_ARGS+=(-v "$HOME/.gitconfig:/root/.gitconfig:ro")
  fi
fi

# Script that runs inside the container to set up SSH keys from the mount,
# then exec's into the real entrypoint.
SSH_INIT='
  if [ -d /tmp/host-ssh ]; then
    cp /tmp/host-ssh/config /root/.ssh/config 2>/dev/null || true
    cat /tmp/host-ssh/*.pub > /root/.ssh/authorized_keys 2>/dev/null || true
    # Copy private keys for direct git operations (container-local, ephemeral)
    for f in /tmp/host-ssh/*; do
      name=$(basename "$f")
      case "$name" in known_hosts|authorized_keys|*.pub|config) continue ;; esac
      [ -f "$f" ] && cp "$f" /root/.ssh/ && chmod 600 "/root/.ssh/$name"
    done
    chmod 600 /root/.ssh/authorized_keys 2>/dev/null || true
    chmod 600 /root/.ssh/config 2>/dev/null || true
  fi
'

case "$MODE" in
  interactive)
    if $SSH_MODE; then
      docker run -d --name "$CONTAINER" \
        -p "$SSH_PORT":22 \
        "${MOUNT_ARGS[@]}" \
        "$IMAGE" bash -c "$SSH_INIT exec /usr/sbin/sshd -D" >/dev/null
      echo ""
      echo "Sandbox running with SSH + git credentials. Connect with:"
      echo ""
      echo "  ssh -o StrictHostKeyChecking=no -p $SSH_PORT root@localhost"
      echo ""
      echo "Your ~/.ssh and ~/.gitconfig are mounted (keys copied into container)."
      echo "Git auth works for all your configured profiles."
      echo ""
      echo "Or connect directly:"
      echo ""
      echo "  docker exec -it $CONTAINER bash"
    else
      docker run -d --name "$CONTAINER" "$IMAGE" sleep infinity >/dev/null
      echo ""
      echo "Sandbox running. Connect with:"
      echo ""
      echo "  docker exec -it $CONTAINER bash"
    fi
    echo ""
    echo "Inside the container:"
    echo "  equip                                 # on PATH (~/.local/bin)"
    echo "  ~/run-tests                             # run the full test suite"
    echo "  source ~/setup.sh && sandbox_init       # set up agents without running tests"
    echo ""
    echo "Cleanup: docker rm -f $CONTAINER"
    ;;

  test)
    echo "Running tests..."
    echo ""
    if $SSH_MODE; then
      docker run --rm --name "$CONTAINER" "${MOUNT_ARGS[@]}" "$IMAGE" \
        bash -c "$SSH_INIT exec /root/run-tests"
    else
      docker run --rm --name "$CONTAINER" "$IMAGE" /root/run-tests
    fi
    ;;

  keep-alive)
    echo "Starting sandbox container (keep-alive mode)..."
    if $SSH_MODE; then
      docker run -d --name "$CONTAINER" "${MOUNT_ARGS[@]}" "$IMAGE" \
        bash -c "$SSH_INIT /root/run-tests; echo; echo 'Tests finished. Container alive for exploration.'; exec sleep infinity" >/dev/null
    else
      docker run -d --name "$CONTAINER" "$IMAGE" \
        bash -c '/root/run-tests; echo ""; echo "Tests finished. Container alive for exploration."; exec sleep infinity' >/dev/null
    fi

    echo "Streaming test output (ctrl-c to stop following)..."
    echo ""
    docker logs -f "$CONTAINER"

    echo ""
    echo "Container is still running. Explore with:"
    echo ""
    echo "  docker exec -it $CONTAINER bash"
    echo ""
    echo "Inside the container:"
    echo "  cat ~/.local/share/equip/sandbox.log  # full test log"
    echo "  tree ~/.local/share/equip/            # cache structure"
    echo "  equip list                            # all skills"
    echo "  equip status                          # installed state"
    echo "  ls ~/.claude/skills/                    # installed skills"
    echo ""
    echo "Cleanup: docker rm -f $CONTAINER"
    ;;
esac
