#!/usr/bin/env bash
# 与 AGENTS.md 一致：VIP 问答实例 workspace 根目录下 knowledge/ 为只读挂载（symlink），
# 指向 vip-admin workspace（与实例目录同父级）下的共享 knowledge/。
# 实例内 memory/、MEMORY.md 等仍在本 workspace，不由本脚本链接。
#
# 用法：由安装器在 post_install 中调用；需传入本实例 workspace 绝对路径，或设置：
#   WORKSPACE=/path/to/workspace_<INSTANCE_ID> ./scripts/setup_links.sh
#   或 OPENCLAW_WORKSPACE=... ./scripts/setup_links.sh
#   或 ./scripts/setup_links.sh /path/to/workspace_<INSTANCE_ID>

set -euo pipefail

WS="${WORKSPACE:-${OPENCLAW_WORKSPACE:-${1:-}}}"
if [[ -z "$WS" ]]; then
  echo "setup_links: set WORKSPACE or OPENCLAW_WORKSPACE, or pass the instance workspace root as the first argument." >&2
  exit 1
fi

WS="$(cd "$WS" && pwd)"
parent="$(dirname "$WS")"
admin_knowledge="${parent}/knowledge"
link="${WS}/knowledge"

if [[ ! -d "$admin_knowledge" ]]; then
  echo "setup_links: admin knowledge directory not found: ${admin_knowledge}" >&2
  echo "setup_links: install vip-admin first so ${admin_knowledge} exists." >&2
  exit 1
fi

mkdir -p "$WS"

if [[ -e "$link" && ! -L "$link" ]]; then
  echo "setup_links: ${link} exists and is not a symlink; refusing to replace." >&2
  exit 1
fi

rm -f "$link"
ln -sfn "$(cd "$admin_knowledge" && pwd)" "$link"
echo "setup_links: ${link} -> $(readlink "$link")"
