#!/bin/bash
# verify_syncscript.sh
#
# 驗證 syncscript / syncscript_optimized 同步結果一致性
#
# 用法:
#   verify_syncscript.sh snapshot <out-file>   拍快照存到檔
#   verify_syncscript.sh diff <file-a> <file-b> 比對兩個快照
#   verify_syncscript.sh help                   顯示說明
#
# 典型流程:
#   verify_syncscript.sh snapshot /tmp/before.txt
#   syncscript                                   # 或 syncscript_optimized
#   verify_syncscript.sh snapshot /tmp/after.txt
#   verify_syncscript.sh diff /tmp/before.txt /tmp/after.txt
#
# AB 對比（舊 vs 優化）:
#   syncscript                                   # 舊版
#   verify_syncscript.sh snapshot /tmp/old.txt
#   syncscript_optimized                         # 優化版
#   verify_syncscript.sh snapshot /tmp/new.txt
#   verify_syncscript.sh diff /tmp/old.txt /tmp/new.txt

set -o pipefail

SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes"
SYNC_FILES=".gamerc bin .psqlrc .functions .bash_xl .bash_profile .bashrc"

usage() {
    sed -n '3,18p' "$0" | sed 's/^# \?//'
    exit "${1:-0}"
}

# 自己實作 print_servername（從 /etc/hosts 查 IP 對應的首個 hostname）
_servername_by_ip() {
    awk -v ip="$1" '$1==ip { print $2; exit }' /etc/hosts
}

collect_ips() {
    # 仿 syncscript：/etc/hosts BELOW~ABOVE 區段 + （若 CTRL）TEST IP
    sed -n '/BELOW/,/ABOVE/p' /etc/hosts | grep "^[0-9]" | awk '{print $1}'
    local me="$(hostname)"
    if grep -q "CTRL" <<< "$me"; then
        grep -i TEST ~/bin/hosts 2>/dev/null | awk '{print $1}' | head -1
    fi
}

snapshot() {
    local OUT="$1"
    [ -z "$OUT" ] && { echo "錯誤：需指定 output 檔路徑" >&2; exit 1; }

    > "$OUT"
    local COUNT=0
    for IP in $(collect_ips); do
        local HN
        HN=$(_servername_by_ip "$IP")
        [ -z "$HN" ] && HN="(unknown)"
        echo "=== $HN ($IP) ===" >> "$OUT"
        ssh $SSH_OPTS "$IP" "cd ~ && find $SYNC_FILES -type f -exec md5sum {} \; 2>/dev/null | grep -v '\.gamerc\$' | sort; grep '^HOST_NAME=' .gamerc" >> "$OUT" 2>&1 \
            || echo "(ssh failed)" >> "$OUT"
        COUNT=$((COUNT + 1))
    done
    echo "Snapshot: $COUNT hosts → $OUT"
}

do_diff() {
    local A="$1" B="$2"
    [ -z "$A" ] || [ -z "$B" ] && { echo "錯誤：需指定兩個快照檔" >&2; exit 1; }
    [ -f "$A" ] && [ -f "$B" ] || { echo "錯誤：檔案不存在 ($A, $B)" >&2; exit 1; }

    if diff -q "$A" "$B" > /dev/null; then
        echo "✅ 一致（兩個快照完全相同）"
    else
        echo "⚠️ 有差異："
        diff "$A" "$B"
        exit 2
    fi
}

case "${1:-help}" in
    snapshot) shift; snapshot "${1:-}" ;;
    diff)     shift; do_diff "${1:-}" "${2:-}" ;;
    help|-h|--help) usage 0 ;;
    *) echo "未知命令: $1" >&2; usage 1 ;;
esac
