#!/bin/bash
# 交互式多机互联脚本

# 交互选择IP获取方式
select_ip_mode() {
    whiptail --title "选择IP获取方式" --menu "请选择IP地址获取方式：" 15 50 4 \
        "1" "手动输入IP地址" \
        "2" "自动扫描同网段IP" \
        3>&1 1>&2 2>&3
}

# 手动输入IP地址
manual_ip_input() {
    IPLIST=()
    echo "请输入需要连接的IP地址（每行一个，输入空行结束）："
    while true; do
        read -p "IP地址: " ip
        [[ -z $ip ]] && break
        if [[ $ip =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            IPLIST+=("$ip")
        else
            echo "错误：$ip 不是有效的IP地址"
        fi
    done
}

# 自动扫描IP
auto_scan_ip() {
    IP=$(ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
    NET=${IP%.*}.
    
    END=$(whiptail --inputbox "请输入扫描范围上限(1-254)" 10 40 "254" 3>&1 1>&2 2>&3)
    [[ -z $END ]] && END=254

    echo "正在扫描存活IP..."
    rm -f SCANIP.log
    for((i=1;i<="$END";i++));do
        ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
    done
    wait
    IPLIST=($(cat SCANIP.log 2>/dev/null))
}

# 密码验证函数
get_password() {
    while true; do
        PASS=$(whiptail --passwordbox "请输入SSH密码" 10 40 3>&1 1>&2 2>&3)
        [[ -z $PASS ]] && continue
        
        PASS_CONFIRM=$(whiptail --passwordbox "请再次确认密码" 10 40 3>&1 1>&2 2>&3)
        if [[ "$PASS" != "$PASS_CONFIRM" ]]; then
            whiptail --msgbox "两次输入的密码不一致，请重新输入！" 10 40
        else
            break
        fi
    done
}

# 主程序
main() {
    # 选择IP获取方式
    case $(select_ip_mode) in
        1) manual_ip_input ;;
        2) auto_scan_ip ;;
        *) exit ;;
    esac

    # 检查IP列表
    if [ ${#IPLIST[@]} -eq 0 ]; then
        whiptail --msgbox "未找到有效的IP地址！" 10 40
        exit 1
    fi

    # 获取密码
    get_password

    # 显示配置信息
    whiptail --yesno "即将配置以下IP：\n${IPLIST[*]}\n\n确认继续操作吗？" 20 60
    [[ $? -ne 0 ]] && exit

    # 准备SSH环境
    rm -f /root/.ssh/id_rsa*
    ssh-keygen -P "" -f /root/.ssh/id_rsa -q

    # 安装依赖
    . /etc/os-release
    if [[ $ID = "centos" || $ID = "rocky" ]]; then
        rpm -q sshpass || yum -y install sshpass
    else
        dpkg -l | grep -q sshpass || { apt update; apt -y install sshpass; }
    fi

    # 主配置循环
    for ip in "${IPLIST[@]}"; do
        {
            # 跳过本机
            [[ $ip == $IP ]] && continue

            # 配置SSH互信
            if sshpass -p "$PASS" ssh-copy-id -o StrictHostKeyChecking=no root@$ip &>/dev/null; then
                # 分发SSH配置
                sshpass -p "$PASS" scp -o StrictHostKeyChecking=no -r /root/.ssh root@$ip:/
                
                # 分发known_hosts
                scp /root/.ssh/known_hosts root@$ip:.ssh/
                
                echo "[成功] $ip 配置完成"
            else
                echo "[失败] $ip 无法连接" >&2
            fi
        } &
    done
    wait

    whiptail --msgbox "所有主机配置完成！" 10 40
}

# 执行主程序
main