#!/bin/bash
source "$HOME/.gamerc"
set -euo pipefail

usage() {
  echo "Usage: $0 <DB_TYPE> <MACHINE1> [MACHINE2 ...]" >&2
  exit 2
}

[[ $# -lt 2 ]] && usage
ACTION="$1"; shift

case "${ACTION}" in
  ACCOUNTDB|GAMEDB|WORLDDB|SOCIETYDB)
    param="${ACTION}"
    ;;
  *)
    echo "ERROR: DB_TYPE must be 'ACCOUNTDB' or 'GAMEDB' or 'WORLDDB' or 'SOCIETYDB'" >&2
    usage
    ;;
esac

# dbpatch_tools 完成狀態（你原本寫死 "1"）
return_code="1"

# 單次 ssh 探測的 hard timeout（避免 ssh hang）
: "${CHECK_SSH_TIMEOUT_SEC:=10}"

# 單次檢查：全部 host 都回 return_code 才輸出 "2"
fail=0

for host in "$@"; do
  result="$(
    timeout "${CHECK_SSH_TIMEOUT_SEC}" ssh \
      -o BatchMode=yes \
      -o ConnectTimeout=5 \
      -o StrictHostKeyChecking=accept-new \
      -o ServerAliveInterval=5 \
      -o ServerAliveCountMax=1 \
      "$host" "dbpatch_tools ${param}" </dev/null 2>/dev/null \
    || true
  )"

  # 去掉 CR/LF/前後空白，避免比對失敗
  result="$(printf '%s' "$result" | tr -d '\r\n' | xargs || true)"

  if [[ "$result" != "$return_code" ]]; then
    fail=1
  fi
done

if (( fail == 0 )); then
  echo "2"
  exit 0
else
  echo "-2"
  exit 1
fi
