#!/bin/bash
# install-linux-guard.sh - 在 Linux 上安装 myclaw-sync systemd 守卫
# 前提：已经手动运行过 mc server <name> 完成注册（config.json 已存在）

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_ok()   { echo -e "${GREEN}[OK]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_err()  { echo -e "${RED}[ERR]${NC} $*"; }
log_info() { echo -e "     $*"; }

echo ""
echo "=== MyClaw Linux 守卫安装 ==="
echo ""

# ── 1. 检查 config.json 是否存在（必须先注册）─────────────────────────────
CONFIG_FILE="$HOME/.openclaw/myclaw/server/config.json"
if [ ! -f "$CONFIG_FILE" ]; then
  log_err "config.json 不存在: $CONFIG_FILE"
  log_info "请先手动运行一次注册："
  log_info "  mc server <你的名字>"
  log_info "注册成功后再运行本脚本。"
  exit 1
fi

CLAW_NAME=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE')).get('claw','?'))" 2>/dev/null || echo "unknown")
log_ok "检测到注册名: $CLAW_NAME"

# ── 2. 复制 guard 脚本到用户目录 ─────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GUARD_DEST="$HOME/.openclaw/myclaw/server/myclaw-guard.sh"

cp "$SCRIPT_DIR/myclaw-guard.sh" "$GUARD_DEST"
chmod +x "$GUARD_DEST"
log_ok "guard 脚本: $GUARD_DEST"

# ── 3. 安装 systemd user service ─────────────────────────────────────────
SERVICE_DIR="$HOME/.config/systemd/user"
mkdir -p "$SERVICE_DIR"

SERVICE_DEST="$SERVICE_DIR/myclaw-sync.service"
cp "$SCRIPT_DIR/myclaw-sync.service" "$SERVICE_DEST"
log_ok "service 文件: $SERVICE_DEST"

# ── 4. 重载 systemd 并启用 ───────────────────────────────────────────────
systemctl --user daemon-reload
log_ok "systemd daemon-reload 完成"

systemctl --user enable myclaw-sync
log_ok "开机自启: 已启用"

# ── 5. 开启 lingering（SSH 断开后 user service 继续跑）────────────────────
if command -v loginctl &>/dev/null; then
  loginctl enable-linger "$USER" 2>/dev/null && log_ok "loginctl linger: 已启用（断开 SSH 不影响服务）" \
    || log_warn "loginctl linger 失败，可能需要 root 权限: sudo loginctl enable-linger $USER"
else
  log_warn "loginctl 不可用，请手动确认 SSH 断开后服务能否持续"
fi

# ── 6. 启动服务 ──────────────────────────────────────────────────────────
systemctl --user restart myclaw-sync
sleep 2

STATUS=$(systemctl --user is-active myclaw-sync 2>/dev/null || echo "unknown")
if [ "$STATUS" = "active" ]; then
  log_ok "服务状态: $STATUS"
else
  log_warn "服务状态: $STATUS（等几秒后重试，或查看日志）"
fi

# ── 7. 打印日志路径和常用命令 ─────────────────────────────────────────────
echo ""
echo "=== 安装完成 ==="
echo ""
echo "日志文件:  $HOME/.openclaw/logs/myclaw-guard.log"
echo ""
echo "常用命令:"
echo "  查看状态    systemctl --user status myclaw-sync"
echo "  查看日志    tail -f ~/.openclaw/logs/myclaw-guard.log"
echo "  重启服务    systemctl --user restart myclaw-sync"
echo "  停止服务    systemctl --user stop myclaw-sync"
echo "  卸载守卫    systemctl --user disable --now myclaw-sync"
echo ""
