#!/bin/bash
# diff_run_merge.sh — 比對 tools 部署的 run_merge_n1_clean 跟 ~/bin/run_merge_n1_clean 差異
# 用法: diff_run_merge.sh <tools|tools-dev>
# 使用 diff -rq 逐 byte 雙向比對（不依賴 size+mtime）
# --no-dereference: 不跟進 symlink，避免 broken link 噴 "No such file" 錯誤

set -eu

P1="${1:-}"
if [[ "$P1" != "tools" && "$P1" != "tools-dev" ]]; then
    echo "用法: $0 <tools|tools-dev>"
    exit 1
fi

SRC="$HOME/www/$P1/scripts/bin/run_merge_n1_clean"
DST="$HOME/bin/run_merge_n1_clean"

for d in "$SRC" "$DST"; do
    if [[ ! -d "$d" ]]; then
        echo "❌ 目錄不存在: $d"
        exit 1
    fi
done

echo "SRC: $SRC"
echo "DST: $DST"
echo

# diff -rq: recursive, 只印差異摘要
# 退出碼：0=相同, 1=有差異, >1=錯誤
set +e
diff -rq --no-dereference \
    --exclude='merge_n1' \
    --exclude='test_merge_world_directory_template' \
    "$SRC" "$DST"
rc=$?
set -e

echo
if [[ $rc -eq 0 ]]; then
    echo "✓ 完全一致（扣除 merge_n1/、test_merge_world_directory_template/）"
elif [[ $rc -eq 1 ]]; then
    echo "✗ 有差異（見上方清單）"
else
    echo "❌ diff 執行錯誤 (rc=$rc)"
    exit $rc
fi
