#!/bin/bash

# 函数：复制文件到所有IP机器
# 用法: copy_to_ips <source_file> <destination_path>
copy_to_ips() {
    local source_file=$1
    local dest_path=$2
    while IFS= read -r ip; do
        ip=$(echo "$ip" | tr -d '\r')  # 移除DOS换行符
        if [ -n "$ip" ]; then
            echo "Copying $source_file to $ip:$dest_path"
            sshpass -p alpine scp -o StrictHostKeyChecking=no "$source_file" "root@$ip:$dest_path"
        fi
    done < ips.txt
}

# 函数：在所有IP机器上执行命令
# 用法: execute_on_ips <command>
execute_on_ips() {
    local command=$1
    if [ ! -f ips.txt ]; then
        echo "Error: ips.txt not found"
        return 1
    fi
    echo "Total lines in ips.txt: $(wc -l < ips.txt)"
    while IFS= read -r ip; do
        ip=$(echo "$ip" | tr -d '\r')  # 移除DOS换行符
        echo "Read IP: '$ip'"
        if [ -n "$ip" ]; then
            echo "Processing IP: $ip"
            echo "Executing on $ip: $command"
            sshpass -p alpine ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 "root@$ip" "$command" || echo "Failed to execute on $ip"
        else
            echo "Skipping empty line"
        fi
    done < ips.txt
    echo "Finished processing all IPs"
}

# 示例用法（可注释掉）
# copy_to_ips ./251128-nt-01.deb /User/Downlodas
execute_on_ips "killall -9 SpringBoard"