#!/bin/bash
set -euo pipefail

# 核心配置（三主节点+模板存/opt/）
TEMPLATE_URL="http://116.205.97.109/scripts/kubeadm-conf.yaml"
LOCAL_TEMPLATE="/opt/k8s-install-conf/kubeadm-conf.yaml"
PAUSE_ALI_REG="registry.cn-hangzhou.aliyuncs.com/google_containers/pause"
PAUSE_TARGET_REG="registry.k8s.io/pause"
NERDCTL_CMD="nerdctl -n k8s.io"

[ -d "/opt/k8s-install-conf/" ] || sudo mkdir -p /opt/k8s-install-conf/ 
# 三主节点参数
LOCALIP=""
HOSTNAME=""
K8SVERSION=""
CLUSTER_VIP=""
CLUSTER_PORT=""
MASTER01_IP=""
MASTER02_IP=""
MASTER03_IP=""

# 日志函数
info() { echo -e "\033[1;33m[INFO] $1\033[0m"; }
success() { echo -e "\033[0;32m[SUCCESS] $1\033[0m"; }
error() { echo -e "\033[0;31m[ERROR] $1\033[0m" >&2; exit 1; }

# 1. 解析三主节点参数
parse_args() {
    while [[ $# -gt 0 ]]; do
        [[ "$1" =~ ^--([a-z0-9-]+)=(.*)$ ]] || error "参数格式：--key=value（例--master2-ip=192.168.61.132）"
        local key="${BASH_REMATCH[1]}"
        local val="${BASH_REMATCH[2]}"
        case "$key" in
            local-ip) LOCALIP="$val" ;;
            hostname) HOSTNAME="$val" ;;
            k8s-version) K8SVERSION="$val" ;;
            cluster-vip) CLUSTER_VIP="$val" ;;
            cluster-port) CLUSTER_PORT="$val" ;;
            master1-ip) MASTER01_IP="$val" ;;
            master2-ip) MASTER02_IP="$val" ;;
            master3-ip) MASTER03_IP="$val" ;;
            help) 
                echo "三主节点用法：$0 --local-ip=IP --hostname=名 --k8s-version=版 --cluster-vip=IP --cluster-port=端口 --master1-ip=IP --master2-ip=IP --master3-ip=IP"
                exit 0
                ;;
            *) error "未知参数：--$key" ;;
        esac
        shift 1
    done
    # 必选参数校验
    [[ -z "$LOCALIP" || -z "$HOSTNAME" || -z "$K8SVERSION" || -z "$CLUSTER_VIP" || -z "$CLUSTER_PORT" || -z "$MASTER01_IP" ]] && \
    error "缺必选参数！至少需要--local-ip --hostname --k8s-version --cluster-vip --cluster-port --master1-ip"
    # 可选参数默认值
    [[ -z "$MASTER02_IP" ]] && MASTER02_IP="$MASTER01_IP"
    [[ -z "$MASTER03_IP" ]] && MASTER03_IP="$MASTER01_IP"
    # 参数预览
    info "三主节点确认：$MASTER01_IP（主1） | $MASTER02_IP（主2） | $MASTER03_IP（主3）"
}

# 2. 下载模板（修复wget参数：--retry→--tries）
download_template() {
    info "下载模板到$LOCAL_TEMPLATE"
    [[ -w "$(dirname "$LOCAL_TEMPLATE")" ]] || error "/opt/无写入权限"
    # 修复：wget无--retry，用--tries=3（重试3次）+ --retry-connrefused（连接拒绝时重试）
    wget -q -O "$LOCAL_TEMPLATE" \
         --tries=3 \
         --retry-connrefused \
         --waitretry=2 \
         "$TEMPLATE_URL" || error "模板下载失败（检查网络）"
    [[ -s "$LOCAL_TEMPLATE" ]] || error "模板为空"
    success "模板保存到：$LOCAL_TEMPLATE"
}

# 3. 替换三主节点变量
replace_variables() {
    info "替换模板变量（含三主节点IP）"
    sed -i "s/LOCALIP/$LOCALIP/g; s/HOSTNAME/$HOSTNAME/g; s/K8SVERSION/$K8SVERSION/g" "$LOCAL_TEMPLATE"
    sed -i "s/CLUSTER_VIP/$CLUSTER_VIP/g; s/CLUSTER_PORT/$CLUSTER_PORT/g" "$LOCAL_TEMPLATE"
    sed -i "s/MASTER01_IP/$MASTER01_IP/g; s/MASTER02_IP/$MASTER02_IP/g; s/MASTER03_IP/$MASTER03_IP/g" "$LOCAL_TEMPLATE"
    sed -i "s/CLUSTER_VIP:CLUSTER_PORT/${CLUSTER_VIP}:${CLUSTER_PORT}/g" "$LOCAL_TEMPLATE"
    success "变量替换完成"
}

# 4. 拉取K8s镜像
pull_images() {
    info "拉取K8s镜像（配置：$LOCAL_TEMPLATE）"
    kubeadm config images pull --config "$LOCAL_TEMPLATE" || error "镜像拉取失败"
    success "镜像拉取完成"
}

# 5. nerdctl打pause标签
tag_pause() {
    local pause_version=$($NERDCTL_CMD images | grep -v "none" | grep "$PAUSE_ALI_REG" | awk '{print $2}' | head -n1)
    [[ -z "$pause_version" ]] && error "未找到pause镜像"
    info "pause版本：$pause_version"
    $NERDCTL_CMD tag "$PAUSE_ALI_REG:$pause_version" "$PAUSE_TARGET_REG:$pause_version" || error "Tag失败"
    success "pause Tag完成"
}

# 主流程
main() {
    echo -e "\033[1;33m=== 三主节点K8s模板脚本（修复版） ===\033[0m\n"
    parse_args "$@"
    download_template
    replace_variables
    pull_images
    tag_pause

    echo -e "\n\033[0;32m=== 所有操作完成！==="
    echo -e "模板路径：$LOCAL_TEMPLATE"
    echo -e "初始化命令：kubeadm init --config $LOCAL_TEMPLATE\033[0m"
}

main "$@"