#!/bin/bash

SCRIPT_DIR="$(dirname "$(realpath "$0")")"
EXECUTABLE="$SCRIPT_DIR/bin/safe_cli"

# Re-quote each argument for OptionParser.split. `--detach` is for this script only.
DETACH=false
SAFE_CLI_ARGS=""
for arg in "$@"; do
  if [ "$arg" = "--detach" ]; then
    DETACH=true
    continue
  fi
  escaped="${arg//\"/\\\"}"          # escape any double quotes inside the arg
  SAFE_CLI_ARGS="$SAFE_CLI_ARGS \"$escaped\""
done
export SAFE_CLI_ARGS="${SAFE_CLI_ARGS# }"  # trim leading space

export SAFE_NO_ARGS_ACTON="help"
export RELEASE_DISTRIBUTION=none

# Double fork: the subshell exits at once, so the VM is re-parented to init/launchd, outside
# the caller's process tree, and has no terminal. `safe mcp` spawns `safe mcp --serve` so.
# Only errors are kept: the announcement on stdout carries the token.
if $DETACH; then
  LOG="$HOME/.safe/mcp-serve.log"
  mkdir -p "$(dirname "$LOG")"
  ( umask 077; nohup "$EXECUTABLE" start </dev/null >/dev/null 2>>"$LOG" & )
  exit 0
fi

if tty >/dev/null 2>&1; then
  exec "$EXECUTABLE" start < /dev/tty
else
  exec "$EXECUTABLE" start
fi
