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

ENV_FILE="${MNOTE_LIGHTRAG_ENV_FILE:-/mnt/Data1T/Mnote_data/lightrag/LightRAG/.env}"
NPX="${MNOTE_NPX:-npx}"

read_env_value() {
  local key="$1"
  local file="$2"
  if [[ ! -f "$file" ]]; then
    return 0
  fi
  grep -E "^${key}=" "$file" | tail -n 1 | sed -E "s/^${key}=//" | sed -E 's/^"(.*)"$/\1/' | sed -E "s/^'(.*)'$/\1/"
}

HOST_VALUE="${LIGHTRAG_HOST:-$(read_env_value HOST "$ENV_FILE")}"
PORT_VALUE="${LIGHTRAG_PORT:-$(read_env_value PORT "$ENV_FILE")}"
API_KEY_VALUE="${LIGHTRAG_API_KEY:-$(read_env_value LIGHTRAG_API_KEY "$ENV_FILE")}"

HOST_VALUE="${HOST_VALUE:-127.0.0.1}"
PORT_VALUE="${PORT_VALUE:-9621}"

export LIGHTRAG_SERVER_URL="${LIGHTRAG_SERVER_URL:-http://${HOST_VALUE}:${PORT_VALUE}}"
export LIGHTRAG_API_KEY="$API_KEY_VALUE"
export LIGHTRAG_TIMEOUT_MS="${LIGHTRAG_TIMEOUT_MS:-180000}"

exec "$NPX" -y l-pw2c-lightrag-server-mcp@1.2.2 "$@"
