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

INSTALL_ROOT_WIN="${1:?missing Windows install root mounted path}"
CODE_SERVER_VERSION="${2:-4.96.4}"

AGENT_HOME="$HOME/.researchpad-agent"
WEB_HOME="$HOME/.researchpad-agent-web"
CS_DIR="$AGENT_HOME/code-server"
CS_BIN="$CS_DIR/bin/code-server"
LOG_DIR="$WEB_HOME/logs"
WIN_HELPER_DIR="$AGENT_HOME/windows"

mkdir -p "$AGENT_HOME" "$WEB_HOME/User" "$WEB_HOME/extensions" "$LOG_DIR" "$WIN_HELPER_DIR"

echo "[ResearchPad] Installing WSL backend"

if command -v sudo >/dev/null 2>&1; then
  sudo apt-get update -y
  sudo apt-get install -y curl ca-certificates tar gzip procps
fi

if [ ! -x "$CS_BIN" ]; then
  arch="$(uname -m)"
  case "$arch" in
    x86_64|amd64) cs_arch="amd64" ;;
    aarch64|arm64) cs_arch="arm64" ;;
    *) echo "Unsupported WSL architecture: $arch" >&2; exit 1 ;;
  esac

  file="code-server-${CODE_SERVER_VERSION}-linux-${cs_arch}.tar.gz"
  url="https://github.com/coder/code-server/releases/download/v${CODE_SERVER_VERSION}/${file}"
  tmp="/tmp/${file}"
  echo "[ResearchPad] Downloading code-server: $url"
  curl -fL "$url" -o "$tmp"
  rm -rf "$CS_DIR"
  mkdir -p "$CS_DIR"
  tar xzf "$tmp" --strip-components=1 -C "$CS_DIR"
  rm -f "$tmp"
fi

if [ -f "$INSTALL_ROOT_WIN/build/defaults/settings.json" ] && [ ! -f "$WEB_HOME/User/settings.json" ]; then
  cp "$INSTALL_ROOT_WIN/build/defaults/settings.json" "$WEB_HOME/User/settings.json"
fi
if [ -f "$INSTALL_ROOT_WIN/build/defaults/roo-code-settings.json" ]; then
  cp "$INSTALL_ROOT_WIN/build/defaults/roo-code-settings.json" "$WEB_HOME/roo-code-settings.json"
fi

cat > "$WEB_HOME/config.yaml" <<'YAML'
bind-addr: 127.0.0.1:8080
auth: none
disable-telemetry: true
disable-update-check: true
YAML

shopt -s nullglob
for vsix in "$INSTALL_ROOT_WIN"/extensions/*.vsix; do
  echo "[ResearchPad] Installing extension: $(basename "$vsix")"
  "$CS_BIN" --install-extension "$vsix" \
    --user-data-dir "$WEB_HOME/User" \
    --extensions-dir "$WEB_HOME/extensions" \
    --force >/dev/null 2>&1 || true
done

cp "$INSTALL_ROOT_WIN/wsl/start-wsl-agent.sh" "$WIN_HELPER_DIR/start-wsl-agent.sh"
chmod +x "$WIN_HELPER_DIR/start-wsl-agent.sh"

echo "[ResearchPad] WSL backend installed"
