#!/bin/bash

# K3s 高可用集群安装脚本 - 精简版
# 支持主节点和从节点安装，使用国内镜像源

set -e

# 配置
MODE=""                    # server 或 agent
TOKEN=""                   # 集群令牌
SERVER_URL=""              # 主节点地址
NODE_NAME=""               # 节点名称
NODE_IP=""                 # 节点 IP

# 国内镜像源
export INSTALL_K3S_MIRROR=cn

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

# 帮助
help() {
    echo "K3s 高可用集群安装脚本"
    echo
    echo "用法: $0 [选项]"
    echo
    echo "安装模式:"
    echo "  -m, --mode MODE        server: 主节点, agent: 从节点"
    echo
    echo "从节点参数:"
    echo "  -t, --token TOKEN      主节点令牌"
    echo "  -s, --server URL       主节点地址 (如: https://10.206.16.5:6443)"
    echo "  -n, --name NAME        节点名称"
    echo "  -i, --ip IP            节点IP"
    echo
    echo "示例:"
    echo "  # 主节点"
    echo "  $0 -m server"
    echo
    echo "  # 从节点"
    echo "  $0 -m agent -t K10::server -s https://10.206.16.5:6443 -n worker-1 -i 192.168.1.100"
    exit 0
}

# 解析参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -m|--mode) MODE="$2"; shift 2 ;;
        -t|--token) TOKEN="$2"; shift 2 ;;
        -s|--server) SERVER_URL="$2"; shift 2 ;;
        -n|--name) NODE_NAME="$2"; shift 2 ;;
        -i|--ip) NODE_IP="$2"; shift 2 ;;
        -h|--help) help ;;
        *) echo -e "${RED}错误: 未知选项 $1${NC}"; help ;;
    esac
done

# 检查参数
[[ -z "$MODE" ]] && { echo -e "${RED}错误: 必须指定安装模式${NC}"; help; exit 1; }
[[ "$MODE" != "server" && "$MODE" != "agent" ]] && { echo -e "${RED}错误: 模式必须是 server 或 agent${NC}"; exit 1; }
[[ "$MODE" == "agent" && (-z "$TOKEN" || -z "$SERVER_URL") ]] && { echo -e "${RED}错误: 从节点必须提供 token 和 server${NC}"; exit 1; }

# 检查权限
[[ $(id -u) -ne 0 ]] && { echo -e "${RED}错误: 需要 root 权限${NC}"; exit 1; }

echo "=== K3s 高可用集群安装 ==="
echo -e "模式: ${GREEN}$MODE${NC}"
echo -e "镜像源: ${GREEN}国内镜像 (INSTALL_K3S_MIRROR=cn)${NC}"
[[ "$MODE" == "agent" ]] && echo -e "主节点: ${GREEN}$SERVER_URL${NC}"
echo

# 1. 卸载旧版本
if command -v k3s &> /dev/null; then
    echo "卸载旧版本..."
    [[ "$MODE" == "server" ]] && /usr/local/bin/k3s-uninstall.sh || /usr/local/bin/k3s-agent-uninstall.sh
    rm -rf /etc/rancher/k3s/ /var/lib/rancher/k3s/
    echo "✅ 旧版本已卸载"
fi

# 2. 系统配置
echo "配置系统..."
# 禁用 swap
swapoff -a && sed -i '/ swap / s/^/#/' /etc/fstab

# 加载模块
cat > /etc/modules-load.d/k8s.conf <<EOF
br_netfilter
overlay
EOF
modprobe br_netfilter overlay

# 内核参数
cat > /etc/sysctl.d/k8s.conf <<EOF
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
EOF
sysctl --system

# 安装依赖
command -v apt &> /dev/null && apt update && apt install -y curl
command -v yum &> /dev/null && yum install -y curl

echo "✅ 系统配置完成"

# 3. 配置镜像源
echo "配置镜像源..."
mkdir -p /etc/rancher/k3s/
cat > /etc/rancher/k3s/registries.yaml <<EOF
mirrors:
  registry.local.w7.cc:
  docker.io:
    endpoint:
      - "https://mirror.ccs.tencentyun.com"
      - "https://registry.cn-hangzhou.aliyuncs.com"
      - "https://docker.m.daocloud.io"
      - "https://docker.1panel.live"
  quay.io:
    endpoint:
      - "https://quay.m.daocloud.io"
      - "https://quay.dockerproxy.com"
  gcr.io:
    endpoint:
      - "https://gcr.m.daocloud.io"
      - "https://gcr.dockerproxy.com"
  ghcr.io:
    endpoint:
      - "https://ghcr.m.daocloud.io"
      - "https://ghcr.dockerproxy.com"
  k8s.gcr.io:
    endpoint:
      - "https://k8s-gcr.m.daocloud.io"
      - "https://k8s.dockerproxy.com"
  registry.k8s.io:
    endpoint:
      - "https://k8s.m.daocloud.io"
      - "https://k8s.dockerproxy.com"
  mcr.microsoft.com:
    endpoint:
      - "https://mcr.m.daocloud.io"
      - "https://mcr.dockerproxy.com"
  nvcr.io:
    endpoint:
      - "https://nvcr.m.daocloud.io"
  "*":
EOF
echo "✅ 镜像源配置完成"

# 4. 安装 k3s
echo "安装 k3s..."
if [[ "$MODE" == "server" ]]; then
    # 主节点
    export INSTALL_K3S_EXEC="--disable=traefik --cluster-init"
    curl -sfL https://rancher-mirror.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn sh -

    # 获取令牌
    echo
    echo -e "${GREEN}=== 主节点安装完成 ===${NC}"
    echo -e "节点令牌: ${YELLOW}$(cat /var/lib/rancher/k3s/server/node-token)${NC}"
    echo -e "集群信息: ${YELLOW}kubectl cluster-info${NC}"

else
    # 从节点
    export K3S_URL="$SERVER_URL"
    export K3S_TOKEN="$TOKEN"

    # 构建从节点的 EXEC 参数（不包含 --disable=traefik）
    AGENT_EXEC=""
    [[ -n "$NODE_NAME" ]] && AGENT_EXEC="$AGENT_EXEC --node-name=$NODE_NAME"
    [[ -n "$NODE_IP" ]] && AGENT_EXEC="$AGENT_EXEC --node-ip=$NODE_IP --node-external-ip=$NODE_IP"
    export INSTALL_K3S_EXEC="$AGENT_EXEC"

    curl -sfL https://rancher-mirror.rancher.cn/k3s/k3s-install.sh | INSTALL_K3S_MIRROR=cn sh -

    echo
    echo -e "${GREEN}=== 从节点安装完成 ===${NC}"
    echo -e "服务状态: ${YELLOW}systemctl status k3s-agent${NC}"
fi

# 5. 验证
echo "验证安装..."
sleep 10
SERVICE_NAME="k3s$([[ "$MODE" == "agent" ]] && echo "-agent")"

if systemctl is-active --quiet $SERVICE_NAME; then
    echo -e "${GREEN}✅ $SERVICE_NAME 运行正常${NC}"
else
    echo -e "${RED}❌ $SERVICE_NAME 启动失败${NC}"
    echo "日志: journalctl -u $SERVICE_NAME -f"
    exit 1
fi

echo
echo -e "${GREEN}=== 安装成功 ===${NC}"
echo
echo "常用命令:"
if [[ "$MODE" == "server" ]]; then
    echo "  kubectl get nodes -o wide"
    echo "  kubectl get pods -A"
    echo "  sudo systemctl status k3s"
else
    echo "  sudo systemctl status k3s-agent"
    echo "  在主节点检查: kubectl get nodes"
fi