#!/usr/bin/env bash
# Expose one project directory to ChatGPT through an OpenAI Secure MCP Tunnel.
#
#   gptbridge run <workspace> [--sandbox-mode MODE] [--network] [--readable-root PATH]
#   gptbridge doctor
#   gptbridge serve <workspace> [...]   # the MCP server alone, on stdio, for debugging
set -euo pipefail

ROOT="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"
STATE="${GPTBRIDGE_HOME:-${HOME}/.gptbridge}"
ENV_FILE="${STATE}/env"
KEY_FILE="${STATE}/api-key"
PYTHON="${ROOT}/venv/bin/python"
TUNNEL_CLIENT="${ROOT}/vendor/tunnel-client"

die() { echo "gptbridge: $*" >&2; exit 1; }

require_install() {
  [ -x "$PYTHON" ] || die "not installed: run ${ROOT}/install.sh"
  [ -x "$TUNNEL_CLIENT" ] || die "tunnel-client missing: run ${ROOT}/install.sh"
}

load_credentials() {
  [ -f "$ENV_FILE" ] || die "missing ${ENV_FILE}; see ${ROOT}/README.md"
  # shellcheck disable=SC1090
  set -a; . "$ENV_FILE"; set +a
  [ -n "${CONTROL_PLANE_TUNNEL_ID:-}" ] || die "CONTROL_PLANE_TUNNEL_ID is not set in ${ENV_FILE}"
  [ -f "$KEY_FILE" ] || die "missing ${KEY_FILE} (the runtime API key, mode 0600)"
  local perms; perms="$(stat -c '%a' "$KEY_FILE")"
  [ "$perms" = "600" ] || die "${KEY_FILE} is mode ${perms}; run: chmod 600 ${KEY_FILE}"
}

command_name="${1:-}"; shift || true

case "$command_name" in
  serve)
    require_install
    exec "$PYTHON" "${ROOT}/mcp_server.py" --workspace "$@"
    ;;

  run)
    require_install
    load_credentials
    workspace="${1:-}"; shift || true
    [ -n "$workspace" ] || die "usage: gptbridge run <workspace> [--sandbox-mode MODE] [--network]"
    workspace="$("$PYTHON" -c 'import sys;sys.path.insert(0,sys.argv[1]);from workspace import resolve_workspace;print(resolve_workspace(sys.argv[2]))' "$ROOT" "$workspace")"
    # tunnel-client takes the server as ONE flattened string, so a path or flag
    # carrying whitespace or a comma silently becomes different arguments.
    for word in "$workspace" "$@"; do
      case "$word" in
        *[[:space:],]*) die "argument contains whitespace or a comma, which tunnel-client cannot carry: ${word}" ;;
      esac
    done
    echo "gptbridge: exposing ${workspace} via tunnel ${CONTROL_PLANE_TUNNEL_ID}" >&2
    exec "$TUNNEL_CLIENT" run \
      --control-plane.tunnel-id "$CONTROL_PLANE_TUNNEL_ID" \
      --control-plane.api-key "file:${KEY_FILE}" \
      --mcp.command "command=${PYTHON} ${ROOT}/mcp_server.py --workspace ${workspace} $*" \
      --pid.file "${STATE}/tunnel-client.pid"
    ;;

  doctor)
    require_install
    "$PYTHON" -c 'import mcp; print("mcp sdk:", mcp.__version__ if hasattr(mcp, "__version__") else "installed")'
    "$TUNNEL_CLIENT" version 2>/dev/null || "$TUNNEL_CLIENT" --version
    command -v bwrap >/dev/null && echo "bubblewrap: $(command -v bwrap)" || die "bwrap not on PATH"
    if [ -f "$ENV_FILE" ] && [ -f "$KEY_FILE" ]; then
      echo "credentials: present in ${STATE}"
    else
      echo "credentials: NOT configured — create ${ENV_FILE} and ${KEY_FILE} (see ${ROOT}/README.md)"
    fi
    ;;

  *)
    sed -n '2,6p' "$(readlink -f "${BASH_SOURCE[0]}")" | sed 's/^# \?//'
    exit 1
    ;;
esac
