#!/bin/bash
#***************************************************************#
# ScriptName: quk3sconfig.sh
# Author: xhy
# Create Date: 2025-03-15 02:02
# Modify Author: xhy
# Modify Date: 2025-03-19 11:17
# Version: v1
#***************************************************************#

#######################################
# 全局变量配置区
#######################################
echo -e "\n\033[33m[INFO] 开始定义全局参数...\033[0m"
sleep 1

declare -A NODES=(
    [master01]="172.24.8.181"
    [master02]="172.24.8.182"
    [master03]="172.24.8.183"
    [master04]="172.24.8.184"
    [master05]="172.24.8.185"
    [master06]="172.24.8.186"
)

# 公共参数
K3SHA_VIP="172.24.8.180"
K3SHA_PORT="6443"
K3SHA_AUTH="ilovek3s"
K3SHA_PODCIDR="10.10.0.0/16"
K3SHA_SVCCIDR="10.20.0.0/16"
K3SHA_DNSIP="10.20.0.10"
K3SHA_NETINF="eth0"

echo -e "\n\033[32m[SUCCESS] 全局参数定义已完成...\033[0m"

set -euo pipefail  # 启用严格模式

#######################################
# 函数定义区
#######################################
# 创建目录结构
init_dirs() {
    echo -e "\n\033[33m[INFO] 开始创建目录结构...\033[0m"
    sleep 1
    
    for node in "${!NODES[@]}"; do
        mkdir -p k3sdir/${node}/{keepalived,haproxy,init}
    done
    mkdir -p k3sdir/{keepalived,haproxy,init}

    echo -e "\n\033[32m[SUCCESS] 目录结构创建已完成...\033[0m"
}

# 下载基础配置文件
download_templates() {
    echo -e "\n\033[33m[INFO] 开始下载模板文件...\033[0m"
    sleep 1
    
    # Keepalived模板
    wget -qcP k3sdir/keepalived/ http://down.linuxsb.com/mydeploy/k3s/common/{k3s-keepalived.conf.tpl,check_apiserver.sh}
    
    # HAProxy模板
    wget -qcP k3sdir/haproxy/ http://down.linuxsb.com/mydeploy/k3s/common/{k3s-haproxy.cfg.tpl,k3s-haproxy.service}
    
    # K3s配置模板
    wget -qcP k3sdir/init/ http://down.linuxsb.com/mydeploy/k3s/qk3s-config.yaml.tpl
    wget -qcP k3sdir/init/ https://rancher-mirror.rancher.cn/k3s/k3s-install.sh 
    
    # 分发调度器配置
    for node in "${!NODES[@]}"; do
        wget -qcP "k3sdir/${node}/init/" http://down.linuxsb.com/mydeploy/k3s/scheduler-config.yaml
    done

    echo -e "\n\033[32m[SUCCESS] 模板文件下载已完成...\033[0m"
}

# 生成Keepalived配置
gen_keepalived_conf() {
    echo -e "\n\033[33m[INFO] 开始生成 KeepAlived 配置...\033[0m"
    sleep 1
    
    local priority=120
    for node in "${!NODES[@]}"; do
        sed -e "
            s/K3SHA_KA_STATE/BACKUP/g
            s/K3SHA_KA_INTF/${K3SHA_NETINF}/g
            s/K3SHA_IPLOCAL/${NODES[$node]}/g
            s/K3SHA_KA_PRIO/$((priority++))/g
            s/K3SHA_VIP/${K3SHA_VIP}/g
            s/K3SHA_AUTH/${K3SHA_AUTH}/g
        " k3sdir/keepalived/k3s-keepalived.conf.tpl > "k3sdir/${node}/keepalived/keepalived.conf"
        
        cp k3sdir/keepalived/check_apiserver.sh "k3sdir/${node}/keepalived/"
    done

    echo -e "\n\033[32m[SUCCESS] KeepAlived 配置已完成...\033[0m"
}

# 生成K3s配置文件
gen_k3s_config() {
    echo -e "\n\033[33m[INFO] 开始生成 K3S 配置...\033[0m"
    sleep 1
    
    for node in "${!NODES[@]}"; do
        sed -e "
            s|K3SHA_AUTH|${K3SHA_AUTH}|g
            s|K3SHA_PORT|${K3SHA_PORT}|g
            s|K3SHA_PODCIDR|${K3SHA_PODCIDR}|g
            s|K3SHA_SVCCIDR|${K3SHA_SVCCIDR}|g
            s|K3SHA_DNSIP|${K3SHA_DNSIP}|g
            s|K3SHA_IPLOCAL|${NODES[$node]}|g
        " k3sdir/init/qk3s-config.yaml.tpl > "k3sdir/${node}/init/config.yaml"
    done

    # 创建临时文件并写入基础内容
    cat > /tmp/tmp.txt <<EOF
tls-san:
  - localhost
  - 127.0.0.1
EOF
    
    # 自动遍历所有节点IP（按节点名字母顺序）
    for ip in "${NODES[@]}"; do
        echo "  - $ip" >> /tmp/tmp.txt
    done
    
    # 追加VIP地址
    echo "  - ${K3SHA_VIP}" >> /tmp/tmp.txt

    for node in "${!NODES[@]}"; do
      cat /tmp/tmp.txt >> "k3sdir/${node}/init/config.yaml"
    done
    
    rm -rf /tmp/tmp.txt

    echo -e "\n\033[32m[SUCCESS] K3S 配置已完成...\033[0m"
}

# 生成HAProxy配置
gen_haproxy_conf() {
    echo -e "\n\033[33m[INFO] 生成 HAProxy 配置...\033[0m"
    sleep 1

    local backend_servers=""
    for node_ip in "${NODES[@]}"; do
        backend_servers+="    server ${node_ip} ${node_ip}:${K3SHA_PORT} check\n"
    done
    
    # 使用临时文件处理多行替换
    local tmpfile=$(mktemp)
    echo -e "$backend_servers" > "$tmpfile"

    # 替换模板中的占位符
    sed -e "/BACKSERVER/ {
        r $tmpfile
        d
    }" "k3sdir/haproxy/k3s-haproxy.cfg.tpl" > "k3sdir/haproxy/haproxy.cfg"

    rm -f "$tmpfile"
    
    echo -e "\n\033[32m[SUCCESS] HAProxy 配置已完成...\033[0m"
}

# 分发配置文件
distribute_files() {
    echo -e "\n\033[33m[INFO] 分发配置文件...\033[0m"
    sleep 1

    for node in "${!NODES[@]}"; do
        echo "正在处理节点: $node"

        # HAProxy配置
        cp k3sdir/haproxy/haproxy.cfg k3sdir/${node}/haproxy/
        scp -qp k3sdir/haproxy/haproxy.cfg root@$node:/etc/haproxy/haproxy.cfg
        cp k3sdir/haproxy/k3s-haproxy.service k3sdir/${node}/haproxy/
        scp -qp k3sdir/haproxy/k3s-haproxy.service root@$node:/usr/lib/systemd/system/haproxy.service
    
        # Keepalived配置
        scp -qp k3sdir/$node/keepalived/* root@$node:/etc/keepalived/
        
        # K3s配置
        ssh root@$node "mkdir -p /etc/rancher/k3s"
        scp -qp k3sdir/$node/init/* root@$node:/etc/rancher/k3s/
        chmod u+x k3sdir/init/k3s-install.sh
        scp -qp k3sdir/init/k3s-install.sh root@$node:/root/k3s-install.sh
    done

    echo -e "\n\033[32m[SUCCESS] 配置分发已完成...\033[0m"
}

#######################################
# 主执行流程
#######################################
main() {
    init_dirs
    download_templates
    gen_keepalived_conf
    gen_k3s_config
    gen_haproxy_conf
    distribute_files
    
    # 设置执行权限
    chmod u+x *.sh
    echo -e "\n\033[32m[SUCCESS] 所有配置已完成...\033[0m"
    sleep 1
}

main "$@"
