#!/bin/bash

# 配置参数
DISK_IMAGE="/root/debian-12-generic-amd64.qcow2"
DISK_SIZE="30G"           # 磁盘大小
MEMORY="4096"             # 内存大小 (MB)
SOCKETS="1"               # CPU插槽数
CORES="4"                 # 每个插槽的核心数 (总CPU数 = SOCKETS × CORES)
CPU_TYPE="host"           # CPU 类型设置为 host
STORAGE="local-lvm"       # 存储池名称，根据你的环境修改
ROOT_PASSWORD="J4c8#PLYqnV@rfNx"    # root 用户密码
TOTAL_CPUS=$((SOCKETS * CORES))

# ✅ 新增：并发线程数量。你自己设置（推荐 3~10）
THREADS=5

# ✅ 新增：初始化信号量（用于并发控制）
tmp_fifo="/tmp/vm_fifo_$$"
mkfifo "$tmp_fifo"
exec 9<>"$tmp_fifo"
rm -f "$tmp_fifo"

# 放入 THREADS 个 token，表示可用的并发槽位
for ((i=0; i<THREADS; i++)); do
    echo >&9
done


# ✅✅✅ 新增：从远程下载 ip.txt 并人工确认
REMOTE_URL="https://pan.halocloud.net/?f=/HGC/ip.txt"
TMP_IP_FILE="/tmp/ip.txt"

echo "🌐 正在从远程下载 IP 列表..."
if ! curl -fsSL "$REMOTE_URL" -o "$TMP_IP_FILE"; then
    echo "❌ 无法下载 IP 列表: $REMOTE_URL"
    exit 1
fi

if [ ! -s "$TMP_IP_FILE" ]; then
    echo "❌ 下载的 IP 文件为空"
    exit 1
fi

echo "✅ 已成功下载 IP 列表:"
echo "----------------------------------"
nl -w2 -s'  ' "$TMP_IP_FILE" | head -n 20
if [ "$(wc -l < "$TMP_IP_FILE")" -gt 20 ]; then
    echo "...（共 $(wc -l < "$TMP_IP_FILE") 行，仅显示前 20 行）"
fi
echo "----------------------------------"
read -rp "是否确认以上 IP 列表无误并继续？(y/N): " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
    echo "🚫 已取消操作。"
    rm -f "$TMP_IP_FILE"
    exit 0
fi

# 检查磁盘镜像文件是否存在
if [ ! -f "$DISK_IMAGE" ]; then
    echo "错误: 磁盘镜像文件 $DISK_IMAGE 不存在"
    exit 1
fi


# 获取可用 VMID 的函数，带重试机制
get_available_vmid() {
    while [ $retry -lt $max_retries ]; do
        local vmid=$(pvesh get /cluster/nextid)
        
        # 检查 VMID 是否真的可用
        if ! qm config "$vmid" >/dev/null 2>&1; then
            echo "$vmid"
            return 0
        fi
        
        retry=$((retry + 1))
        echo "VMID $vmid 已被占用，重试中... ($retry/$max_retries)" >&2
        sleep $((RANDOM % 3 + 1))  # 随机延迟 1-3 秒
    done
    
    echo "错误: 无法获取可用的 VMID" >&2
    return 1
}



# 创建虚拟机的函数，带错误处理
create_vm_with_retry() {
    local ipaddr="$1"
    local bridge="$2"
    local max_retries=10
    local retry=0
    
    while [ $retry -lt $max_retries ]; do
        # 推导网关和名称
        ip_prefix=$(echo "$ipaddr" | awk -F. '{print $1"."$2"."$3}')
        gateway="${ip_prefix}.1"
        vmname="${ip_prefix}.0"
        
        # 获取可用的 VMID
        vmid=$(get_available_vmid)
        if [ $? -ne 0 ]; then
            echo "错误: 无法获取可用的 VMID"
            return 1
        fi
        
        echo "即将创建 VM..."
        echo "VMID: $vmid"
        echo "名称: $vmname"
        echo "主IP地址: $ipaddr/24"
        echo "网关: $gateway"
        echo "子网范围: ${ip_prefix}.2-254"
        echo "内存: ${MEMORY}MB"
        echo "CPU拓扑: ${SOCKETS}插槽 × ${CORES}核心 = ${TOTAL_CPUS}个vCPU"
        echo "CPU类型: $CPU_TYPE"
        echo "网桥: $bridge"
        echo "磁盘大小: $DISK_SIZE"
        echo "Root密码: $ROOT_PASSWORD"
        echo "开机自启: 启用"
        
        # 创建虚拟机基础配置，添加开机自启
        if qm create "$vmid" \
            --name "$vmname" \
            --memory "$MEMORY" \
            --sockets "$SOCKETS" \
            --cores "$CORES" \
            --cpu "$CPU_TYPE" \
            --net0 "virtio,bridge=${bridge}" \
            --serial0 socket \
            --vga serial0 \
            --ostype l26 \
            --agent 1 \
            --onboot 1 2>/dev/null; then
            
            echo "虚拟机框架创建成功，正在导入磁盘..."
            
            # 导入磁盘镜像
            if qm importdisk "$vmid" "$DISK_IMAGE" "$STORAGE" 2>/dev/null; then
                echo "磁盘镜像导入成功，正在配置虚拟机..."
                
                # 先附加导入的磁盘
                if qm set "$vmid" --scsi0 "${STORAGE}:vm-${vmid}-disk-0" 2>/dev/null; then
                    
                    echo "磁盘已附加，正在扩容到 ${DISK_SIZE}..."
                    
                    # 扩容磁盘
                    if qm resize "$vmid" scsi0 "$DISK_SIZE" 2>/dev/null; then
                        
                        echo "磁盘扩容成功，正在配置 Cloud-Init..."
                        
                        # 添加 Cloud-Init 磁盘
                        if qm set "$vmid" --ide2 "${STORAGE}:cloudinit" 2>/dev/null; then
                            
                            # 设置启动顺序（从scsi0启动）
                            if qm set "$vmid" --boot "order=scsi0;ide2" 2>/dev/null; then
                                
                                echo "正在创建Cloud-Init用户数据..."
                                
                                mkdir -p /var/lib/vz/snippets
                                
                                cat > "/var/lib/vz/snippets/user-data-${vmid}.yaml" << EOF
#cloud-config
users:
  - name: root
    lock_passwd: false
    plain_text_passwd: ${ROOT_PASSWORD}

ssh_pwauth: true
disable_root: false

write_files:
  - path: /etc/systemd/system/setup-additional-ips.service
    content: |
      [Unit]
      Description=Setup Additional IP Addresses
      After=network.target
      Wants=network.target

      [Service]
      Type=oneshot
      ExecStart=/usr/local/bin/setup-additional-ips.sh
      RemainAfterExit=true

      [Install]
      WantedBy=multi-user.target
    permissions: '0644'
  - path: /usr/local/bin/setup-additional-ips.sh
    content: |
      #!/bin/bash
      # 添加子网所有IP地址
EOF

                                for i in $(seq 2 254); do
                                    current_ip="${ip_prefix}.${i}"
                                    if [ "$current_ip" != "$ipaddr" ]; then
                                        echo "      ip addr add ${current_ip}/24 dev eth0 2>/dev/null || true" >> "/var/lib/vz/snippets/user-data-${vmid}.yaml"
                                    fi
                                done
                                
                                cat >> "/var/lib/vz/snippets/user-data-${vmid}.yaml" << EOF
      echo "Additional IPs configured at \$(date)" > /var/log/additional-ips.log
      ip addr show eth0 >> /var/log/additional-ips.log
    permissions: '0755'

runcmd:
  - sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
  - sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication yes/g' /etc/ssh/sshd_config
  - systemctl restart sshd.service
  - systemctl enable setup-additional-ips.service
  - systemctl start setup-additional-ips.service
  - echo "SSH密码登录已启用，子网IP已配置" > /var/log/setup.log
  - echo "开机自启服务已配置" >> /var/log/setup.log
  - ip addr show eth0 >> /var/log/setup.log

package_update: false
package_upgrade: false
EOF

                                if qm set "$vmid" \
                                    --ciuser "root" \
                                    --cipassword "$ROOT_PASSWORD" \
                                    --ipconfig0 "ip=${ipaddr}/24,gw=${gateway}" \
                                    --nameserver "47.83.25.51" \
                                    --searchdomain "local" \
                                    --cicustom "user=local:snippets/user-data-${vmid}.yaml" 2>/dev/null; then
                                    
                                    echo "虚拟机配置完成，正在启动..."
                                    
                                    # 启动虚拟机
                                    if qm start "$vmid" 2>/dev/null; then
                                        #echo "虚拟机 $vmid ($vmname) 已创建并启动。"
                                        #echo "主网络配置: ${ipaddr}/24, 网关: ${gateway}"
                                        #echo "子网IP范围: ${ip_prefix}.2-253 (共252个IP)"
                                        #echo "磁盘大小已扩容到: $DISK_SIZE"
                                        #echo "默认用户: root, 密码: $ROOT_PASSWORD"
                                        #echo "SSH密码登录: 将自动启用"
                                        #echo "开机自启: 已启用"
                                        #echo "SSH访问: ssh root@<任意子网IP>"
                                        #echo "配置日志: /var/log/setup.log"
                                        #echo "IP配置日志: /var/log/additional-ips.log"
                                        #echo "可通过 Proxmox Web 控制台的 xterm.js 访问"
                                        #echo ""
                                        #echo "注意: 虚拟机启动后约1-2分钟完成配置"
                                        #echo "重要: IP配置已通过systemd服务持久化，重启后自动恢复"
                                        #echo "可以通过以下命令检查配置状态:"
                                        #echo "- ip addr show eth0"
                                        #echo "- cat /var/log/setup.log"
                                        #echo "- cat /var/log/additional-ips.log"
                                        #echo "- systemctl status setup-additional-ips.service"
                                        #echo "- systemctl status sshd"
                                        #echo ""
                                        #echo "手动扩展文件系统 (在虚拟机内执行):"
                                        #echo "growpart /dev/sda 1 && resize2fs /dev/sda1"
                                        
                                        echo "虚拟机 $vmid ($vmname) 已创建并启动，用户数据文件保留。"
                                        echo "----------------------------------------"
                                        return 0
                                    else
                                        echo "警告: 虚拟机 $vmid 创建成功但启动失败"
                                        return 0
                                    fi
                                else
                                    echo "错误: 配置 Cloud-Init 设置失败"
                                fi
                            else
                                echo "错误: 设置启动顺序失败"
                            fi
                        else
                            echo "错误: 添加 Cloud-Init 磁盘失败"
                        fi
                    else
                        echo "错误: 磁盘扩容失败"
                    fi
                else
                    echo "错误: 附加主磁盘失败"
                fi
            else
                echo "错误: 导入磁盘镜像失败"
            fi
            
            echo "清理失败的虚拟机..."
            qm destroy "$vmid" 2>/dev/null
        else
            echo "警告: VMID $vmid 创建失败"
        fi
        
        retry=$((retry + 1))
        echo "重试中... ($retry/$max_retries)"
        sleep $((RANDOM % 5 + 2))
    done
    
    echo "错误: 创建虚拟机失败，已达到最大重试次数"
    return 1
}



###############################################
# ✅ ✅ ✅   多线程并发读取 ip.txt 的核心逻辑   ✅ ✅ ✅
###############################################

while IFS= read -r line || [ -n "$line" ]; do
    if [ -z "$line" ] || [[ "$line" =~ ^[[:space:]]*# ]]; then
        continue
    fi
    line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

    if [ -n "$line" ]; then
        ipaddr=$(echo "$line" | awk '{print $1}')
        bridge=$(echo "$line" | awk '{print $2}')
        if [ -z "$bridge" ]; then
            bridge="vmbr0"
            echo "警告: IP $ipaddr 未指定网桥，使用默认网桥 $bridge"
        fi
        if [[ ! "$ipaddr" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "错误: IP地址格式无效: $ipaddr"
            continue
        fi

        echo "正在处理 IP: $ipaddr, 网桥: $bridge"
        read -u 9
        {
            create_vm_with_retry "$ipaddr" "$bridge"
            echo >&9
        } &
    fi
done < "$TMP_IP_FILE"

wait
rm -f "$TMP_IP_FILE"

echo "所有虚拟机创建完成。"
#echo ""
#echo "重要提醒："
#echo "1. 每个虚拟机已配置自动添加整个子网的IP地址"
#echo "2. SSH密码登录将自动启用"
#echo "3. 虚拟机启动后约1-2分钟完成所有配置"
#echo "4. 可通过子网内任意IP访问虚拟机"
#echo "5. 登录信息: 用户名root, 密码: $ROOT_PASSWORD"
#echo "6. 需要手动扩展文件系统"
#echo "7. 所有Cloud-Init用户数据文件已自动清理"
#echo "8. 开机自启已启用"
#echo "9. IP配置通过systemd服务持久化，重启后自动恢复"
#echo ""
#echo "检查配置命令:"
#echo "- ip addr show eth0  # 查看所有绑定的IP"
#echo "- cat /var/log/setup.log  # 查看配置日志"
#echo "- cat /var/log/additional-ips.log  # 查看IP配置日志"
#echo "- systemctl status setup-additional-ips.service  # 查看IP配置服务状态"
#echo "- ssh root@<任意子网IP>  # 测试SSH登录"
#echo "- sudo reboot  # 测试重启后IP是否自动恢复"


# 显示所有保留的用户数据文件
echo ""
echo "保留的用户数据文件列表："
user_data_files=$(ls /var/lib/vz/snippets/user-data-*.yaml 2>/dev/null)
if [ -n "$user_data_files" ]; then
    ls -la /var/lib/vz/snippets/user-data-*.yaml 2>/dev/null
    echo ""
    echo "这些文件包含了每个虚拟机的完整配置信息"
else
    echo "没有找到用户数据文件"
fi
