#!/bin/bash
#***************************************************************#
# ScriptName: dockersysncimages
# Author: xhy
# Create Date: 2025-03-18 10:51
# Modify Author: xhy
# Modify Date: 2025-07-21 21:38
# Version: v2.0
#***************************************************************#

# 配置参数
REMOTE_SOURCE_DIR="/root/images"
LOCAL_TARGET_DIR="/root/images"
TARGET_HOSTS=("master02" "master03" "worker01" "worker02" "worker03")
SSH_USER="root"
SSH_OPTS="-o ConnectTimeout=5 -o StrictHostKeyChecking=no"

# 安装 rsync
yum -y install rsync

# 简单日志输出
log() {
    echo -e "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 检查并创建本地目录
[[ -d "$LOCAL_TARGET_DIR" ]] || mkdir -p "$LOCAL_TARGET_DIR"

# 遍历所有目标主机
for host in "${TARGET_HOSTS[@]}"; do
    echo -e "\n\n\033[33m[INFO] 正在同步 ${host} 主机至本地目录 ${LOCAL_TARGET_DIR} ...\033[0m"

    # 使用 SSH 检测主机可用性
    if ! ssh ${SSH_OPTS} "${SSH_USER}@${host}" "exit" &>/dev/null; then
        log "\033[31m[ERROR] 无法连接 ${host}, 跳过...\033[0m"
        continue
    fi

    # 安装 rsync
    ssh ${SSH_OPTS} "${SSH_USER}@${host}" "yum -y install rsync"

    # 执行同步
    rsync -av --ignore-existing -e "ssh ${SSH_OPTS}" \
        "${SSH_USER}@${host}:${REMOTE_SOURCE_DIR}/" "${LOCAL_TARGET_DIR}/"
    echo -e "\n\n\033[32m[SUCC] ${host} 同步至本地目录已完成...\033[0m"
    echo "----------------------------------"
done

echo -e "\n\n\033[32m[SUCC] >>> 所有主机同步至本地已完成...\033[0m"

sleep 3
# 遍历所有目标主机
for host in "${TARGET_HOSTS[@]}"; do
    echo -e "\n\n\033[33m[INFO] 正在同步本地目录 ${LOCAL_TARGET_DIR} 至 ${host} 主机 ...\033[0m"

    # 使用 SSH 检测主机可用性
    if ! ssh ${SSH_OPTS} "${SSH_USER}@${host}" "exit" &>/dev/null; then
        log "\033[31m[ERROR] 无法连接 ${host}, 跳过...\033[0m"
        continue
    fi

    # 执行同步
    rsync -av --ignore-existing -e "ssh ${SSH_OPTS}" \
        "${LOCAL_TARGET_DIR}/" "${SSH_USER}@${host}:${REMOTE_SOURCE_DIR}/"
    echo -e "\n\n\033[32m[SUCC] 本地目录同步至 ${host} 已完成...\033[0m"
    echo "----------------------------------"
done


