#!/usr/bin/env bash
# 金值 Flutter web 版本化部署。
# 产物须已在 build/web（先 flutter build web）。本脚本负责：打包 → scp → 远端解到
# 带版本号的 rev 目录 → 原子切换 cur 软链。旧 rev 全部保留，便于随时回滚。
#
# 用法：tool/deploy_web.sh <rev_id>
#   rev_id   版本标识（CI 传 run_number；本地传时间戳）
#
# 连接参数（环境变量覆盖；CI 由 secrets 注入）：
#   DEPLOY_HOST / DEPLOY_USER / DEPLOY_PORT / WORKPATH
set -euo pipefail

REV="${1:?用法: tool/deploy_web.sh <rev_id>}"

DEPLOY_HOST="${DEPLOY_HOST:-47.114.117.126}"
DEPLOY_USER="${DEPLOY_USER:-dev}"
DEPLOY_PORT="${DEPLOY_PORT:-59650}"
WORKPATH="${WORKPATH:-/opt/modules/front/jinzhi/flutter}"

SSH_OPTS="-o StrictHostKeyChecking=accept-new -p $DEPLOY_PORT"
SCP_OPTS="-o StrictHostKeyChecking=accept-new -P $DEPLOY_PORT"  # scp 端口是大写 -P
BUILD_DIR="build/web"
PKG="jinzhi-web-$REV.tar.gz"

[ -d "$BUILD_DIR" ] || { echo "✗ 缺少 $BUILD_DIR，请先 flutter build web"; exit 1; }

echo "▶ 打包 $BUILD_DIR → $PKG"
tar -C "$BUILD_DIR" -czf "$PKG" .

echo "▶ scp → $DEPLOY_USER@$DEPLOY_HOST:/tmp/$PKG"
scp $SCP_OPTS "$PKG" "$DEPLOY_USER@$DEPLOY_HOST:/tmp/$PKG"

echo "▶ 远端：解到 rev_${REV}、切 cur（旧 rev 全部保留）"
# shellcheck disable=SC2087
ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" \
  "REV='$REV' WORKPATH='$WORKPATH' PKG='$PKG' bash -s" <<'REMOTE'
set -euo pipefail
REVDIR="$WORKPATH/core/revs/rev_$REV"
mkdir -p "$REVDIR"
tar -C "$REVDIR" -xzf "/tmp/$PKG"
rm -f "/tmp/$PKG"
# 原子切换：-f 覆盖、-n 不跟随已存在的软链目录
ln -sfn "$REVDIR" "$WORKPATH/cur"
echo "OK: cur -> rev_$REV，现存版本：$(ls -1d "$WORKPATH"/core/revs/rev_* | sort -r | tr '\n' ' ')"
REMOTE

rm -f "$PKG"
echo "✅ 已部署 rev_$REV → https://jinzhi.h5.local/flutter/（no-cache，刷新即新版）"
