#!/bin/bash
# myclaw-guard.sh - MyClaw Sync 守卫包装脚本
# 职责：探测环境、打印完整日志、持续守卫 mc server
# 用法: nohup bash myclaw-guard.sh >> ~/.openclaw/logs/myclaw-guard.log 2>&1 &

LOG_DIR="$HOME/.openclaw/logs"
LOG_FILE="$LOG_DIR/myclaw-guard.log"
mkdir -p "$LOG_DIR"

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

log "========================================"
log "myclaw-guard 启动"
log "USER=$USER  HOME=$HOME  PID=$$"
log "原始 PATH=$PATH"

# ── 加载 shell 环境（探测 nvm / fnm / volta 等） ──────────────────────────
for rc in \
  "$HOME/.profile" \
  "$HOME/.bash_profile" \
  "$HOME/.bashrc" \
  "$HOME/.zshrc" \
  "$HOME/.nvm/nvm.sh" \
  "$HOME/.config/nvm/nvm.sh" \
  "/usr/local/share/nvm/nvm.sh" \
  "$HOME/.volta/bin/../load.sh" \
  "$HOME/.fnm/fnm.env"; do
  if [ -f "$rc" ]; then
    log "加载 rc: $rc"
    # shellcheck disable=SC1090
    source "$rc" 2>/dev/null || true
  fi
done

# 手动追加常见 bin 路径（覆盖 nvm/npm global 等）
for extra_path in \
  "$HOME/.nvm/versions/node/$(ls $HOME/.nvm/versions/node 2>/dev/null | sort -V | tail -1)/bin" \
  "$HOME/.volta/bin" \
  "$HOME/.fnm/aliases/default/bin" \
  "$HOME/.local/bin" \
  "$HOME/.npm-global/bin" \
  "/usr/local/bin" \
  "/usr/bin"; do
  if [ -d "$extra_path" ]; then
    export PATH="$extra_path:$PATH"
  fi
done

log "探测后 PATH=$PATH"

# ── 探测 node ─────────────────────────────────────────────────────────────
NODE_BIN=$(command -v node 2>/dev/null || echo "")
if [ -n "$NODE_BIN" ]; then
  NODE_VER=$("$NODE_BIN" --version 2>/dev/null || echo "unknown")
  log "node: $NODE_BIN  ($NODE_VER)"
else
  log "警告: 未找到 node"
fi

# ── 探测 mc ───────────────────────────────────────────────────────────────
MC_BIN=$(command -v mc 2>/dev/null || echo "")

if [ -z "$MC_BIN" ]; then
  log "which mc 未找到，尝试常见路径..."
  for candidate in \
    "/usr/local/bin/mc" \
    "/usr/bin/mc" \
    "$HOME/.npm-global/bin/mc" \
    "$HOME/.local/bin/mc" \
    "$HOME/.nvm/versions/node/$(ls $HOME/.nvm/versions/node 2>/dev/null | sort -V | tail -1)/bin/mc" \
    "$HOME/.volta/bin/mc" \
    "$HOME/.fnm/aliases/default/bin/mc"; do
    if [ -x "$candidate" ]; then
      MC_BIN="$candidate"
      log "找到 mc: $MC_BIN"
      break
    fi
  done
fi

if [ -z "$MC_BIN" ]; then
  log "错误: 无法找到 mc 命令，10秒后重试..."
  sleep 10
  exit 1
fi

log "mc: $MC_BIN"

# ── 读取 config.json，打印当前 claw 名 ──────────────────────────────────
CONFIG_FILE="$HOME/.openclaw/myclaw/server/config.json"
if [ -f "$CONFIG_FILE" ]; then
  CLAW_NAME=$(python3 -c "import json,sys; print(json.load(open('$CONFIG_FILE')).get('claw','?'))" 2>/dev/null || cat "$CONFIG_FILE")
  log "config.json: $CONFIG_FILE"
  log "claw name: $CLAW_NAME"
else
  log "错误: config.json 不存在 ($CONFIG_FILE)"
  log "请先手动运行一次 mc server <name> 完成注册"
  exit 1
fi

# ── PID 文件路径 ─────────────────────────────────────────────────────────
PID_FILE="$HOME/.openclaw/.myclaw-sync.pid"
log "pid file: $PID_FILE"
log "========================================"
log ""

# ── 持续守卫循环 ──────────────────────────────────────────────────────────
RESTART_COUNT=0
while true; do
  RESTART_COUNT=$((RESTART_COUNT + 1))
  log "[ 第 $RESTART_COUNT 次启动 ] $MC_BIN server"

  "$MC_BIN" server
  EXIT_CODE=$?

  log "mc server 退出，退出码=$EXIT_CODE，3秒后重启..."
  sleep 3
done
