#!/usr/bin/env bash
# GoCDN 节点安装脚本（自动安装 OpenResty + 节点代理，需 root）
# 用法:
#   ./install-node.sh -master http://主控IP:8080 -name 节点名 -token 节点Token [-f ./gocdn-agent | -u 二进制URL]
set -e

MASTER=""
NAME=""
TOKEN=""
BIN_URL=""
BIN_FILE=""
WORKDIR="/usr/local/gocdn/node"

while getopts "m:n:t:u:f:w:" opt; do
  case $opt in
    m) MASTER="$OPTARG" ;;
    n) NAME="$OPTARG" ;;
    t) TOKEN="$OPTARG" ;;
    u) BIN_URL="$OPTARG" ;;
    f) BIN_FILE="$OPTARG" ;;
    w) WORKDIR="$OPTARG" ;;
    *) echo "用法: $0 -master URL -name 名称 -token TOKEN [-f 本地二进制 | -u URL]"; exit 1 ;;
  esac
done

[ "$(id -u)" -eq 0 ] || { echo "请使用 root 运行"; exit 1; }
[ -n "$MASTER" ] && [ -n "$NAME" ] && [ -n "$TOKEN" ] || {
  echo "错误: -master -name -token 均必填"; exit 1; }

echo "==> [1/4] 安装 OpenResty"
if ! command -v openresty >/dev/null 2>&1; then
  if command -v apt-get >/dev/null 2>&1; then
    apt-get update -y
    apt-get install -y --no-install-recommends wget gnupg ca-certificates lsb-release
    codename=$(lsb_release -sc)
    curl -fsSL https://openresty.org/package/pubkey.gpg | gpg --dearmor -o /usr/share/keyrings/openresty.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/openresty.gpg] http://openresty.org/package/ubuntu $(lsb_release -sc) main" \
      > /etc/apt/sources.list.d/openresty.list
    apt-get update -y && apt-get install -y openresty
  elif command -v dnf >/dev/null 2>&1; then
    dnf install -y dnf-plugins-core
    dnf config-manager --add-repo https://openresty.org/package/centos/openresty.repo 2>/dev/null || \
      dnf config-manager addrepo --from-repofile=https://openresty.org/package/centos/openresty.repo
    dnf install -y openresty
  elif command -v yum >/dev/null 2>&1; then
    yum install -y yum-utils
    yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
    yum install -y openresty
  else
    echo "错误: 未识别的包管理器，请手动安装 OpenResty 后重试"; exit 1
  fi
else
  echo "OpenResty 已安装，跳过"
fi
# gocdn 由 agent 管理 openresty，屏蔽系统默认服务
systemctl stop openresty 2>/dev/null || true
systemctl disable openresty 2>/dev/null || true

echo "==> [2/4] 安装节点代理"
PREFIX="/usr/local/gocdn"
mkdir -p "$WORKDIR"/{conf/sites,conf/lua,logs,run,cache,certs}
BIN="$PREFIX/gocdn-agent"
if [ -n "$BIN_FILE" ]; then
  cp -f "$BIN_FILE" "$BIN"
elif [ -n "$BIN_URL" ]; then
  echo "下载节点程序: $BIN_URL"
  curl -fL --retry 3 -o "$BIN" "$BIN_URL" || wget -qO "$BIN" "$BIN_URL"
else
  if [ -f "./gocdn-agent" ]; then
    cp -f ./gocdn-agent "$BIN"
  else
    echo "错误: 未指定 -f/-u，且当前目录无 gocdn-agent 文件"; exit 1
  fi
fi
chmod +x "$BIN"

echo "==> [3/4] 写入 systemd 服务"
cat > /etc/systemd/system/gocdn-agent.service <<EOF
[Unit]
Description=GoCDN Node Agent
After=network.target

[Service]
Type=simple
ExecStart=$BIN -master $MASTER -name $NAME -token $TOKEN -workdir $WORKDIR
Restart=always
RestartSec=5
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

echo "==> [4/4] 启动"
systemctl daemon-reload
systemctl enable --now gocdn-agent
sleep 2
systemctl --no-pager status gocdn-agent | head -8 || true

# 防火墙放行 80/443
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
  firewall-cmd --permanent --add-service=http --add-service=https >/dev/null 2>&1 || true
  firewall-cmd --reload >/dev/null 2>&1 || true
elif command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "active"; then
  ufw allow 80/tcp 443/tcp >/dev/null 2>&1 || true
fi

echo "======================================================"
echo "GoCDN 节点安装完成！"
echo "  工作目录: $WORKDIR"
echo "  请在主控「站点管理」中将站点分配到本节点（名称: $NAME）"
echo "  服务管理: systemctl {start|stop|restart} gocdn-agent"
echo "  日志:     journalctl -u gocdn-agent -f"
echo "======================================================"
