#!/bin/bash
# 第十輪：風險評估兩份模板上載新 VPS（只換 templates/*.docx，程式碼零改動）
# 用法：先把兩份 docx stage 到 /tmp/ra10_stage/，再 bash /tmp/deploy_ra10_vps.sh
set -u
SITE=/www/wwwroot/00002359.tech
STAGE=/tmp/ra10_stage
M_EC=6743808fbbf3d1deb848ce6752093d72
M_YC=0a56c70fc23a9331ac9c98f75d3b8216
S_EC=164740
S_YC=429341
TS=$(date +%Y%m%d_%H%M%S)
BAK=/root/backup_${TS}_pre_ra10
fail=0

h_ec=$(md5sum "$STAGE/master_ra_mec.docx" | awk '{print $1}')
h_yc=$(md5sum "$STAGE/master_ra_yec.docx" | awk '{print $1}')
echo "stage  mec=$h_ec  yec=$h_yc"
if [ "$h_ec" != "$M_EC" ]; then echo "ABORT：stage mec hash 唔啱"; fail=1; fi
if [ "$h_yc" != "$M_YC" ]; then echo "ABORT：stage yec hash 唔啱"; fail=1; fi
sz_ec=$(stat -c %s "$STAGE/master_ra_mec.docx")
sz_yc=$(stat -c %s "$STAGE/master_ra_yec.docx")
echo "stage  size mec=$sz_ec yec=$sz_yc"
if [ "$sz_ec" != "$S_EC" ]; then echo "ABORT：stage mec size 唔啱"; fail=1; fi
if [ "$sz_yc" != "$S_YC" ]; then echo "ABORT：stage yec size 唔啱"; fail=1; fi
if [ "$fail" != "0" ]; then echo "STOP：stage 核對唔過，未碰正式檔"; exit 1; fi

# 上載前備份（本次只改兩份模板，冇 DB 寫入 ⇒ 冇需要 dump）
mkdir -p "$BAK"
cp -a "$SITE/templates/master_ra_mec.docx" "$BAK/master_ra_mec.docx"
cp -a "$SITE/templates/master_ra_yec.docx" "$BAK/master_ra_yec.docx"
tar czf "$BAK/files.tgz" -C "$BAK" master_ra_mec.docx master_ra_yec.docx
echo "BACKUP $BAK"
ls -l "$BAK"
hb_ec=$(md5sum "$BAK/master_ra_mec.docx" | awk '{print $1}')
hb_yc=$(md5sum "$BAK/master_ra_yec.docx" | awk '{print $1}')
echo "backup hashes mec=$hb_ec yec=$hb_yc"

cp "$STAGE/master_ra_mec.docx" "$SITE/templates/master_ra_mec.docx"
cp "$STAGE/master_ra_yec.docx" "$SITE/templates/master_ra_yec.docx"
chown www:www "$SITE/templates/master_ra_mec.docx" "$SITE/templates/master_ra_yec.docx"
chmod 644 "$SITE/templates/master_ra_mec.docx" "$SITE/templates/master_ra_yec.docx"

echo "== 讀回核對 =="
cd "$SITE/templates" || exit 1
md5sum master_ra_mec.docx master_ra_yec.docx
ls -l --time-style=long-iso master_ra_mec.docx master_ra_yec.docx
rb_ec=$(md5sum master_ra_mec.docx | awk '{print $1}')
rb_yc=$(md5sum master_ra_yec.docx | awk '{print $1}')
if [ "$rb_ec" = "$M_EC" ] && [ "$rb_yc" = "$M_YC" ]; then echo "HASH_ALL_OK"; else echo "HASH_MISMATCH"; exit 1; fi

# 模板改動唔涉及 PHP；照樣 lint 兩個相關 lib（防其他地方郁壞）
PHP=/www/server/php/84/bin/php
"$PHP" -l "$SITE/lib/risk_assessment.php"
"$PHP" -l "$SITE/lib/risk_assessment_doc.php"

echo "== 全站漂移（应只郁 2 檔）=="
cd "$SITE" || exit 1
find . -newermt "2026-11-04 18:30" -type f | sort
DRIFT=$(find . -newermt "2026-11-04 18:30" -type f | wc -l)
echo "DRIFT_COUNT=$DRIFT"
echo "DEPLOY_RA10_DONE BAK=$BAK"
