#!/usr/bin/env bash
set -euo pipefail

# 說明：
#   - 將本機 $HOME/bin/hosts.new 推到 TEST
#   - 在 TEST 上備份 hosts、套用 hosts.new、rewrite_etc_hosts、syncscript
# 安全保護：
#   - hosts.new 必須存在且非空
#   - rsync/ssh 使用一致的 SSH options

SSH_OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null)
HOST="TEST"

LOCAL_HOSTS_NEW="$HOME/bin/hosts.new"
REMOTE_DIR="$HOME/bin"

# hosts.new 必須存在且非空
if [ ! -s "$LOCAL_HOSTS_NEW" ]; then
  echo "ERROR: hosts.new not found or empty: $LOCAL_HOSTS_NEW" >&2
  exit 1
fi

# 推送 hosts.new 到 TEST（rsync 與 ssh option 一致）
rsync -avz -e "ssh ${SSH_OPTS[*]}" "$LOCAL_HOSTS_NEW" "$HOST:$REMOTE_DIR/."

# 遠端套用：備份 -> 覆蓋 -> rewrite -> sync
ssh "${SSH_OPTS[@]}" "$HOST" 'bash -s' <<'REMOTE'
set -euo pipefail

TODATE=$(date +%Y%m%d)
NOWTS=$(date +%Y%m%d%H%M%S)

HOSTS_FILE="$HOME/bin/hosts"
HOSTS_NEW="$HOME/bin/hosts.new"
PREPARE_DIR="$HOME/prepare"

# 基本檢查
if [ ! -f "$HOSTS_FILE" ]; then
  echo "ERROR: hosts file not found: $HOSTS_FILE" >&2
  exit 1
fi
if [ ! -s "$HOSTS_NEW" ]; then
  echo "ERROR: hosts.new not found or empty: $HOSTS_NEW" >&2
  exit 1
fi

mkdir -p "$PREPARE_DIR"

# 備份
cp -arf "$HOSTS_FILE" "$PREPARE_DIR/hosts.${TODATE}.bak"
cp -arf "$HOSTS_FILE" "$HOME/bin/hosts.old"

# 原子切換（同目錄內 mv 通常是原子）
mv -f "$HOSTS_NEW" "$HOSTS_FILE"

# 確保環境與函式存在
if [ ! -f "$HOME/.gamerc" ]; then
  echo "ERROR: missing $HOME/.gamerc on TEST" >&2
  exit 1
fi

# shellcheck disable=SC1090
ACTION="${ACTION:-init}"
export ACTION

set +e
set +u
source "$HOME/.gamerc" "$ACTION"
rc=$?
set -u
set -e

if [ "$rc" -ne 0 ]; then
  echo "ERROR: source $HOME/.gamerc failed, rc=$rc, ACTION=$ACTION" >&2
  exit "$rc"
fi

if ! type rewrite_etc_hosts >/dev/null 2>&1; then
  echo "ERROR: rewrite_etc_hosts not found after sourcing .gamerc" >&2
  exit 1
fi

set +e
set +u
rewrite_etc_hosts
rc=$?
set -u
set -e

if [ "$rc" -ne 0 ]; then
  echo "ERROR: rewrite_etc_hosts failed, rc=$rc" >&2
  exit "$rc"
fi

# 同步到正式環境
if [ ! -x "$HOME/bin/syncscript" ]; then
  echo "ERROR: syncscript not found or not executable: $HOME/bin/syncscript" >&2
  exit 1
fi

"$HOME/bin/syncscript"

echo "OK: applied hosts on TEST at ${NOWTS}" >&2
REMOTE

