#!/bin/bash

SSH_OPTS=(-o StrictHostKeyChecking=no -o BatchMode=yes)

# Parse --mode flag
while [[ "${1:-}" == --* ]]; do
    case "$1" in
        --mode) MERGE_MODE="$2"; shift 2 ;;
        *) echo "Unknown option: $1" >&2; exit 1 ;;
    esac
done

# 依 MERGE_MODE 決定同步目標機器
case "${MERGE_MODE:-single}" in
  single)
    ALL_MACHINES="MERGE"
    COMMON_MACHINE="MERGE"
    ;;
  multiple)
    ALL_MACHINES="MERGE_COMMON MERGE_ASIA MERGE_US MERGE_EU"
    COMMON_MACHINE="MERGE_COMMON"
    ;;
  *)
    echo "Error: unknown MERGE_MODE '${MERGE_MODE}'" >&2
    exit 1
    ;;
esac

# Server 同步
echo "###### Server sync ######"
for machine in ${ALL_MACHINES}; do
  rsync -avz --exclude-from=$HOME/bin/rsync.exclude $HOME/common-TEST/* ${machine}:~/common-TEST/.
done

# config.ini 同步（動態偵測遠端 servers* 目錄）
echo "###### config00.ini sync ######"
for machine in ${ALL_MACHINES}; do
  echo "  偵測 ${machine} 上的 servers* 目錄..."
  remote_dirs=$(ssh "${SSH_OPTS[@]}" "${machine}" "ls -d ~/servers*/ 2>/dev/null | xargs -I{} basename {}" 2>/dev/null) || true

  if [[ -z "$remote_dirs" ]]; then
    echo "  ${machine}: 無 servers* 目錄，跳過"
    continue
  fi

  for dir_name in ${remote_dirs}; do
    echo "  rsync config00.ini -> ${machine}:~/${dir_name}/"
    rsync -avz $HOME/servers1/config00.ini ${machine}:~/${dir_name}/.
  done
done

# Client 同步
echo "###### Client sync ######"
rsync -avz --exclude="setup.txt" $HOME/www/N1-TEST/* ${COMMON_MACHINE}:~/www/N1-TEST/.

# bin 同步更新
echo "###### bin 同步更新 ######"
for machine in ${ALL_MACHINES}; do
  rsync -avz $HOME/bin/* ${machine}:~/bin/.
done

# s_rootcmds.ini 同步更新
echo "###### s_rootcmds.ini ######"
for machine in ${ALL_MACHINES}; do
  rsync -avz $HOME/bin/S_RootCmds.ini_test_n1 $HOME/bin/S_RootCmds.ini_live_n1 ${machine}:~/bin/.
done
