#!/usr/bin/env bash
# Sentinel 探针一键安装/更新/卸载脚本（本文件不含任何密钥，token 由命令行传入）
#
# 安装/更新：
#   curl -fsSL https://files.miao222.top/sentinel/install.sh | bash -s -- --token <TOKEN> [--name 节点名] [--server URL]
# 卸载：
#   curl -fsSL https://files.miao222.top/sentinel/install.sh | bash -s -- --uninstall
#
# 重复运行 = 幂等更新（未显式传的参数保留旧配置）。仅支持 systemd 发行版。
# 脚本为 POSIX sh 兼容：没有 bash 的系统（如 Alpine）把管道目标换成 sh 即可。
set -eu

FILES_URL="${SENTINEL_FILES_URL:-https://files.miao222.top/sentinel}"
SERVER_URL="https://sentinel.miao222.top"
INSTALL_DIR=/opt/sentinel-agent
UNIT=/etc/systemd/system/sentinel-agent.service
TOKEN="" NAME="" SET_SERVER=0 UNINSTALL=0

while [ $# -gt 0 ]; do
    case "$1" in
        --token)  TOKEN="$2"; shift 2 ;;
        --name)   NAME="$2"; shift 2 ;;
        --server) SERVER_URL="$2"; SET_SERVER=1; shift 2 ;;
        --uninstall) UNINSTALL=1; shift ;;
        *) echo "未知参数: $1"; exit 1 ;;
    esac
done

[ "$(id -u)" = 0 ] || { echo "需要 root 运行（curl ... | sudo bash -s -- ...）"; exit 1; }

if [ "$UNINSTALL" = 1 ]; then
    systemctl disable --now sentinel-agent 2>/dev/null || true
    rm -f "$UNIT"
    systemctl daemon-reload 2>/dev/null || true
    rm -rf "$INSTALL_DIR"
    echo "Sentinel 探针已卸载。"
    exit 0
fi

[ -d /run/systemd/system ] || { echo "此系统不是 systemd，暂不支持一键安装。"; exit 1; }

# ---- 确保 python3 (>=3.6) ----
if ! command -v python3 >/dev/null 2>&1; then
    echo "未找到 python3，尝试自动安装……"
    if command -v apt-get >/dev/null 2>&1; then apt-get update -qq && apt-get install -y -qq python3
    elif command -v dnf >/dev/null 2>&1; then dnf install -y -q python3
    elif command -v yum >/dev/null 2>&1; then yum install -y -q python3
    elif command -v apk >/dev/null 2>&1; then apk add --no-cache python3
    elif command -v zypper >/dev/null 2>&1; then zypper -n install python3
    else echo "无法识别包管理器，请手动安装 python3 后重试。"; exit 1; fi
fi
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 6) else 1)' \
    || { echo "python3 版本过低（需要 >= 3.6）"; exit 1; }

# ---- 下载器 ----
fetch() {  # fetch <url> <dest>
    if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
    else echo "需要 curl 或 wget"; exit 1; fi
}

mkdir -p "$INSTALL_DIR"

# ---- 下载探针并校验 ----
echo "下载探针：$FILES_URL/sentinel-agent.py"
fetch "$FILES_URL/sentinel-agent.py" "$INSTALL_DIR/sentinel-agent.py.new"
if fetch "$FILES_URL/manifest.json" "$INSTALL_DIR/.manifest" 2>/dev/null; then
    python3 - <<'PYEOF' || { echo "sha256 校验失败，中止（下载可能被劫持或缓存陈旧）"; exit 1; }
import hashlib, json, sys
m = json.load(open("/opt/sentinel-agent/.manifest"))
h = hashlib.sha256(open("/opt/sentinel-agent/sentinel-agent.py.new", "rb").read()).hexdigest()
sys.exit(0 if h == m.get("sha256") else 1)
PYEOF
else
    echo "（manifest.json 不可用，跳过 sha256 校验——TLS 仍在保护传输）"
fi
python3 -m py_compile "$INSTALL_DIR/sentinel-agent.py.new" || { echo "探针文件无法通过语法检查，中止"; exit 1; }
mv -f "$INSTALL_DIR/sentinel-agent.py.new" "$INSTALL_DIR/sentinel-agent.py"
chmod 755 "$INSTALL_DIR/sentinel-agent.py"

# ---- 写配置（幂等：未显式传的参数保留旧值；首次安装必须给 --token）----
export SA_TOKEN="$TOKEN" SA_NAME="$NAME" SA_DEFAULT_NAME="$(hostname)"
export SA_SERVER="$([ "$SET_SERVER" = 1 ] && echo "$SERVER_URL" || echo "")"
export SA_FALLBACK_SERVER="$SERVER_URL"
python3 - <<'PYEOF'
import json, os
path = "/opt/sentinel-agent/config.json"
cfg = {}
if os.path.exists(path):
    try:
        cfg = json.load(open(path))
    except Exception:
        cfg = {}
if os.environ.get("SA_TOKEN"):
    cfg["token"] = os.environ["SA_TOKEN"]
if os.environ.get("SA_NAME"):
    cfg["name"] = os.environ["SA_NAME"]
if os.environ.get("SA_SERVER"):
    cfg["server_url"] = os.environ["SA_SERVER"]
cfg.setdefault("name", os.environ.get("SA_DEFAULT_NAME") or "unnamed")
cfg.setdefault("server_url", os.environ.get("SA_FALLBACK_SERVER"))
cfg.setdefault("interval", 10)
if not cfg.get("token"):
    raise SystemExit("首次安装必须提供 --token（在 Sentinel 仪表盘或服务端 config.toml 里查看）")
with open(path, "w") as f:
    json.dump(cfg, f, ensure_ascii=False, indent=2)
os.chmod(path, 0o600)
print("配置：节点名 %s → %s" % (cfg["name"], cfg["server_url"]))
PYEOF

# ---- systemd 单元 ----
cat > "$UNIT" <<'EOF'
[Unit]
Description=Sentinel monitoring agent
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/env python3 /opt/sentinel-agent/sentinel-agent.py
Restart=always
RestartSec=5
User=root

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
if systemctl is-active --quiet sentinel-agent; then
    systemctl restart sentinel-agent
else
    systemctl enable --now sentinel-agent
fi

sleep 3
if systemctl is-active --quiet sentinel-agent; then
    echo "── 安装成功，探针运行中 ──"
    journalctl -u sentinel-agent -n 5 --no-pager 2>/dev/null || true
    echo "仪表盘：https://sentinel.miao222.top"
    echo "卸载：curl -fsSL $FILES_URL/install.sh | bash -s -- --uninstall"
else
    echo "── 安装完成但服务未能启动，请检查 ──"
    journalctl -u sentinel-agent -n 20 --no-pager 2>/dev/null || true
    exit 1
fi
