#!/usr/bin/env bash
set -euo pipefail

AGENT_HOME="$HOME/.researchpad-agent"
WEB_HOME="$HOME/.researchpad-agent-web"
CS_BIN="$AGENT_HOME/code-server/bin/code-server"
LOG_DIR="$WEB_HOME/logs"
PID_DIR="$WEB_HOME/pids"

mkdir -p "$LOG_DIR" "$PID_DIR" "$WEB_HOME/User" "$WEB_HOME/extensions"

port_listening() {
  if command -v ss >/dev/null 2>&1; then
    ss -ltn "( sport = :$1 )" | grep -q ":$1"
  elif command -v netstat >/dev/null 2>&1; then
    netstat -ltn | grep -q ":$1 "
  else
    return 1
  fi
}

if [ ! -x "$CS_BIN" ]; then
  echo "code-server not installed: $CS_BIN" >&2
  exit 1
fi

if port_listening 8080; then
  echo "[ResearchPad] code-server already listening on :8080"
  exit 0
fi

nohup "$CS_BIN" \
  --bind-addr 127.0.0.1:8080 \
  --auth none \
  --disable-telemetry \
  --user-data-dir "$WEB_HOME/User" \
  --extensions-dir "$WEB_HOME/extensions" \
  --locale zh-cn \
  --proxy-domain local.researchpad.org \
  > "$LOG_DIR/code-server.log" 2>&1 &

echo "$!" > "$PID_DIR/code-server.pid"
echo "[ResearchPad] code-server started on :8080"
