deploy.prod.sh 27.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
#!/usr/bin/env bash
# 绿纤 ERP · 一键部署正式环境(接口 + 管理后台)
#
# 硬性要求(配置文件保护,多层保险):
#   ★ 正式环境 appsettings.json / appsettings.*.json 绝不覆盖、绝不删除
#   ★ 同步前从发布产物删除配置;rsync 强制排除;dry-run 预检;指纹核对
#   ★ 同步前自动备份正式机配置到 .deploy-staging/config-backup/
#   ★ start-ncc-api.sh / lvqian-erp-crash.env:rsync --delete 排除,同步后从 deploy/prod/ 下发
#   ★ wwwroot/html/(手机端日报 H5):rsync --delete 排除,同步后从「绿纤日报/」下发(勿再用旧的 deploy/prod/html)
#
# 用法:
#   cp deploy.prod.env.example deploy.prod.env   # 首次:填正式路径
#   ./deploy.prod.sh                             # 交互确认后部署
#   ./deploy.prod.sh --yes                       # 跳过确认
#   ./deploy.prod.sh --dry-run                   # 只检查/演练,不写正式目录
#   ./deploy.prod.sh --api-only                  # 只部署接口
#   ./deploy.prod.sh --admin-only                # 只部署管理后台
#   ./deploy.prod.sh --skip-build                # 跳过构建,仅用已有产物同步
#
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
ENV_FILE="${DEPLOY_ENV_FILE:-$ROOT/deploy.prod.env}"
STAGING="$ROOT/.deploy-staging"
API_PROJECT="$ROOT/netcore/src/Application/NCC.API/NCC.API.csproj"
API_DIR="$ROOT/netcore/src/Application/NCC.API"
ADMIN_DIR="$ROOT/antis-ncc-admin"
H5_INDEX="$ROOT/绿纤uni-app/unpackage/dist/build/web/index.html"

DRY_RUN=0
ASSUME_YES=0
DO_API=1
DO_ADMIN=1
SKIP_BUILD=0

for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    --yes|-y) ASSUME_YES=1 ;;
    --api-only) DO_API=1; DO_ADMIN=0 ;;
    --admin-only) DO_API=0; DO_ADMIN=1 ;;
    --skip-build) SKIP_BUILD=1 ;;
    -h|--help)
      sed -n '2,20p' "$0"
      exit 0
      ;;
    *)
      echo "未知参数: ${arg}(可用 --help)" >&2
      exit 1
      ;;
  esac
done

log() { printf '%s\n' "$*"; }
ok() { printf '✅ %s\n' "$*"; }
warn() { printf '⚠️  %s\n' "$*"; }
err() { printf '❌ %s\n' "$*" >&2; }
die() { err "$*"; exit 1; }

# ---------- 加载配置 ----------
if [ ! -f "$ENV_FILE" ]; then
  die "缺少配置文件: $ENV_FILE
请先执行: cp deploy.prod.env.example deploy.prod.env
然后填写正式环境路径后再跑本脚本。"
fi

# shellcheck disable=SC1090
set -a
. "$ENV_FILE"
set +a

DEPLOY_MODE="${DEPLOY_MODE:-local}"
NODE_VERSION="${NODE_VERSION:-16.20.2}"
ADMIN_BUILD_WITH_H5="${ADMIN_BUILD_WITH_H5:-0}"
REQUIRE_EXISTING_APPSETTINGS="${REQUIRE_EXISTING_APPSETTINGS:-1}"
PROD_API_RESTART_REMOTE="${PROD_API_RESTART_REMOTE:-0}"

file_checksum() {
  local f="$1"
  if [ ! -f "$f" ]; then
    echo "MISSING"
    return 0
  fi
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$f" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$f" | awk '{print $1}'
  else
    # 退化:大小+mtime
    wc -c <"$f" | tr -d ' '
  fi
}

# 从发布暂存目录彻底清除受保护配置(任意深度)
strip_protected_configs_from_staging() {
  local dir="$1"
  [ -d "$dir" ] || return 0
  find "$dir" -type f \( \
      -iname 'appsettings.json' -o \
      -iname 'appsettings.*.json' -o \
      -iname 'web.config' -o \
      -iname 'nlog.config' -o \
      -iname 'nlog.*.config' \
    \) -print -delete 2>/dev/null || true

  local leftovers
  leftovers="$(find "$dir" -type f \( \
      -iname 'appsettings.json' -o \
      -iname 'appsettings.*.json' -o \
      -iname 'web.config' -o \
      -iname 'nlog.config' -o \
      -iname 'nlog.*.config' \
    \) 2>/dev/null || true)"
  if [ -n "$leftovers" ]; then
    die "暂存目录仍残留受保护配置,已中止部署:
$leftovers"
  fi
}

load_nvm() {
  export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
  if [ -s "$NVM_DIR/nvm.sh" ]; then
    # shellcheck disable=SC1090
    . "$NVM_DIR/nvm.sh"
  elif [ -s "/usr/local/opt/nvm/nvm.sh" ]; then
    # shellcheck disable=SC1091
    . "/usr/local/opt/nvm/nvm.sh"
  else
    die "未找到 nvm,管理后台构建需要 Node $NODE_VERSION"
  fi
  nvm use "$NODE_VERSION" >/dev/null
  ok "Node $(node -v)"
}

resolve_targets() {
  if [ "$DEPLOY_MODE" = "local" ]; then
    TARGET_API="${PROD_API_DIR:-}"
    TARGET_ADMIN="${PROD_ADMIN_DIR:-}"
    [ -n "$TARGET_API" ] || [ "$DO_API" = "0" ] || die "请在 deploy.prod.env 填写 PROD_API_DIR"
    [ -n "$TARGET_ADMIN" ] || [ "$DO_ADMIN" = "0" ] || die "请在 deploy.prod.env 填写 PROD_ADMIN_DIR"
  elif [ "$DEPLOY_MODE" = "remote" ]; then
    TARGET_API="${REMOTE_API_DIR:-}"
    TARGET_ADMIN="${REMOTE_ADMIN_DIR:-}"
    REMOTE_SSH="${REMOTE_SSH:-}"
    [ -n "$REMOTE_SSH" ] || die "remote 模式请填写 REMOTE_SSH"
    if printf '%s' "$REMOTE_SSH" | grep -Eq '请改成|example\.com|your-prod-host'; then
      die "请先编辑 deploy.prod.env,把 REMOTE_SSH 改成真实服务器,例如 root@1.2.3.4"
    fi
    [ -n "$TARGET_API" ] || [ "$DO_API" = "0" ] || die "请填写 REMOTE_API_DIR"
    [ -n "$TARGET_ADMIN" ] || [ "$DO_ADMIN" = "0" ] || die "请填写 REMOTE_ADMIN_DIR"
    setup_remote_ssh
  else
    die "DEPLOY_MODE 只能是 local 或 remote,当前=$DEPLOY_MODE"
  fi
}

# remote 模式:优先免密公钥;密码仅作兜底(expect 会破坏 rsync 协议,故密码时用 sshpass)
setup_remote_ssh() {
  RSYNC_RSH="ssh -o StrictHostKeyChecking=accept-new -o BatchMode=yes ${REMOTE_SSH_OPTS:-}"
  SSH_WRAPPER=""

  # 公钥可用则直接免密(忽略残留的 REMOTE_SSH_PASSWORD / SSHPASS)
  if ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=8 \
      ${REMOTE_SSH_OPTS:-} "$REMOTE_SSH" 'echo ok' >/dev/null 2>&1; then
    ok "远程登录:SSH 公钥免密"
    return 0
  fi

  if [ -z "${REMOTE_SSH_PASSWORD:-}" ]; then
    die "无法免密登录 ${REMOTE_SSH},且未配置 REMOTE_SSH_PASSWORD。
请先:ssh-copy-id ${REMOTE_SSH}  或在 deploy.prod.env 填写密码。"
  fi

  if command -v sshpass >/dev/null 2>&1; then
    export SSHPASS="$REMOTE_SSH_PASSWORD"
    RSYNC_RSH="sshpass -e ssh -o StrictHostKeyChecking=accept-new ${REMOTE_SSH_OPTS:-}"
    SSH_WRAPPER="sshpass"
    ok "远程登录:使用 sshpass + 密码"
    return 0
  fi

  die "无法免密登录,且本机没有 sshpass(密码 + expect 会弄坏 rsync)。
请安装: brew install hudochenkov/sshpass/sshpass
或配置:ssh-copy-id $REMOTE_SSH"
}

remote_run() {
  if [ "${SSH_WRAPPER:-}" = "sshpass" ]; then
    # shellcheck disable=SC2086
    sshpass -e ssh -o StrictHostKeyChecking=accept-new ${REMOTE_SSH_OPTS:-} "$REMOTE_SSH" "$@"
  elif [ "${SSH_WRAPPER:-}" = "expect" ]; then
    "$STAGING/.ssh_expect_ssh" ${REMOTE_SSH_OPTS:-} "$REMOTE_SSH" "$@"
  else
    # shellcheck disable=SC2086
    ssh -o StrictHostKeyChecking=accept-new ${REMOTE_SSH_OPTS:-} "$REMOTE_SSH" "$@"
  fi
}

remote_test_file() {
  local path="$1"
  remote_run "test -f $(printf '%q' "$path")"
}

remote_checksum() {
  local path="$1"
  remote_run "if [ ! -f $(printf '%q' "$path") ]; then echo MISSING; elif command -v sha256sum >/dev/null 2>&1; then sha256sum $(printf '%q' "$path") | awk '{print \$1}'; elif command -v shasum >/dev/null 2>&1; then shasum -a 256 $(printf '%q' "$path") | awk '{print \$1}'; else wc -c <$(printf '%q' "$path"); fi"
}

# 指纹清单:文件相对路径 -> hash(多文件)
CONFIG_HASH_FILE=""

init_config_hash_store() {
  mkdir -p "$STAGING/config-backup"
  CONFIG_HASH_FILE="$STAGING/config-backup/hashes.before.txt"
  : >"$CONFIG_HASH_FILE"
}

record_config_hash_local() {
  local dir="$1"
  local rel="$2"
  local f="$dir/$rel"
  [ -f "$f" ] || return 0
  printf '%s\t%s\n' "$rel" "$(file_checksum "$f")" >>"$CONFIG_HASH_FILE"
}

record_config_hash_remote() {
  local dir="$1"
  local rel="$2"
  local f="$dir/$rel"
  if ! remote_test_file "$f"; then
    return 0
  fi
  printf '%s\t%s\n' "$rel" "$(remote_checksum "$f")" >>"$CONFIG_HASH_FILE"
}

backup_protected_configs_local() {
  local dir="$1"
  local bak="$STAGING/config-backup/local-$(date +%Y%m%d%H%M%S)"
  mkdir -p "$bak"
  local f name
  for f in "$dir"/appsettings.json "$dir"/appsettings.*.json "$dir"/web.config "$dir"/nlog.config "$dir"/NLog.config "$dir"/nlog.*.config "$dir"/NLog.*.config; do
    [ -e "$f" ] || continue
    [ -f "$f" ] || continue
    name="$(basename "$f")"
    cp -p "$f" "$bak/$name"
    record_config_hash_local "$dir" "$name"
  done
  if [ ! -s "$CONFIG_HASH_FILE" ] && [ "$REQUIRE_EXISTING_APPSETTINGS" = "1" ]; then
    die "正式接口目录缺少 appsettings.json: $dir/appsettings.json
为防止空配置上线,已中止。请确认 PROD_API_DIR 是否正确。"
  fi
  if [ -s "$CONFIG_HASH_FILE" ]; then
    ok "已备份正式配置到 $bak ,并记录指纹"
    cat "$CONFIG_HASH_FILE" | while IFS= read -r line; do log "  指纹 $line"; done
  fi
}

backup_protected_configs_remote() {
  local dir="$1"
  local bak="$STAGING/config-backup/remote-$(date +%Y%m%d%H%M%S)"
  mkdir -p "$bak"
  # 拉取受保护配置做本地备份 + 记指纹
  local names
  names="$(remote_run "cd $(printf '%q' "$dir") && ls -1 appsettings.json appsettings.*.json web.config nlog.config NLog.config nlog.*.config NLog.*.config 2>/dev/null || true")"
  if [ -z "$names" ] && [ "$REQUIRE_EXISTING_APPSETTINGS" = "1" ]; then
    die "远程正式接口目录缺少 appsettings.json: $REMOTE_SSH:$dir/appsettings.json"
  fi
  local name
  while IFS= read -r name; do
    [ -n "$name" ] || continue
    # shellcheck disable=SC2086
    rsync -a -e "$RSYNC_RSH" "$REMOTE_SSH:$dir/$name" "$bak/$name"
    record_config_hash_remote "$dir" "$name"
  done <<<"$names"
  if [ -s "$CONFIG_HASH_FILE" ]; then
    ok "已从远程备份正式配置到 $bak ,并记录指纹"
    cat "$CONFIG_HASH_FILE" | while IFS= read -r line; do log "  指纹 $line"; done
  fi
}

verify_protected_configs_unchanged_local() {
  local dir="$1"
  local rel hash_before hash_after
  local failed=0
  while IFS=$'\t' read -r rel hash_before; do
    [ -n "$rel" ] || continue
    hash_after="$(file_checksum "$dir/$rel")"
    if [ "$hash_after" != "$hash_before" ]; then
      err "致命:正式配置被改动 → $dir/$rel
  部署前: $hash_before
  部署后: $hash_after
  备份目录: $STAGING/config-backup/"
      failed=1
    else
      ok "未覆盖: $rel"
    fi
  done <"$CONFIG_HASH_FILE"
  [ "$failed" = "0" ] || die "配置文件保护校验失败,请立即用 $STAGING/config-backup/ 中的备份恢复"
}

verify_protected_configs_unchanged_remote() {
  local dir="$1"
  local rel hash_before hash_after
  local failed=0
  while IFS=$'\t' read -r rel hash_before; do
    [ -n "$rel" ] || continue
    hash_after="$(remote_checksum "$dir/$rel")"
    if [ "$hash_after" != "$hash_before" ]; then
      err "致命:远程正式配置被改动 → $REMOTE_SSH:$dir/$rel
  部署前: $hash_before
  部署后: $hash_after
  本地备份: $STAGING/config-backup/"
      failed=1
    else
      ok "未覆盖: $rel"
    fi
  done <"$CONFIG_HASH_FILE"
  [ "$failed" = "0" ] || die "配置文件保护校验失败,请立即用 $STAGING/config-backup/ 中的备份恢复到服务器"
}

# rsync 排除规则:配置绝不推/绝不删;同时避开日志/上传等运行时数据
RSYNC_EXCLUDES=(
  --exclude='appsettings.json'
  --exclude='appsettings.*.json'
  --exclude='AppSettings.json'
  --exclude='web.config'
  --exclude='Web.config'
  --exclude='nlog.config'
  --exclude='NLog.config'
  --exclude='nlog.*.config'
  --exclude='NLog.*.config'
  --exclude='logs/'
  --exclude='Logs/'
  --exclude='*.log'
  --exclude='ExportFiles/'
  # 生产运维脚本(不在 publish 产物里;--delete 时绝不可删)
  --exclude='start-ncc-api.sh'
  --exclude='lvqian-erp-crash.env'
  # 接口同步时保护后台页面与上传文件(后台另走 admin 同步)
  --exclude='wwwroot/admin/'
  --exclude='wwwroot/index.html'
  --exclude='wwwroot/UploadFile/'
  --exclude='wwwroot/TemporaryFile/'
  --exclude='wwwroot/h5/'
  # 手机端 web-view 日报静态页(不在 publish 产物里;--delete 绝不可删)
  --exclude='wwwroot/html/'
)

# 同步后写入 crash dump 启动脚本(仓库 deploy/prod/ → 正式目录 + /usr/local/share)
ensure_prod_crash_scripts() {
  local api_dir="$1"
  local src_dir="$ROOT/deploy/prod"
  local start_src="$src_dir/start-ncc-api.sh"
  local env_src="$src_dir/lvqian-erp-crash.env"
  [ -f "$start_src" ] || die "缺少 $start_src"
  [ -f "$env_src" ] || die "缺少 $env_src"

  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] 将下发 crash dump 启动脚本 → $api_dir 与 /usr/local/share/lvqian-erp/"
    return 0
  fi

  if [ "$DEPLOY_MODE" = "local" ]; then
    mkdir -p "$api_dir" /usr/local/share/lvqian-erp /www/wwwlogs/lvqian_erp_crash
    install -m 755 "$start_src" "$api_dir/start-ncc-api.sh"
    install -m 644 "$env_src" "$api_dir/lvqian-erp-crash.env"
    install -m 755 "$start_src" /usr/local/share/lvqian-erp/start-ncc-api.sh
    install -m 644 "$env_src" /usr/local/share/lvqian-erp/lvqian-erp-crash.env
  else
    remote_run "mkdir -p $(printf '%q' "$api_dir") /usr/local/share/lvqian-erp /www/wwwlogs/lvqian_erp_crash"
    if [ "${SSH_WRAPPER:-}" = "sshpass" ]; then
      sshpass -e scp -o StrictHostKeyChecking=accept-new "$start_src" "$env_src" "$REMOTE_SSH:/tmp/"
    else
      scp -o StrictHostKeyChecking=accept-new -o BatchMode=yes "$start_src" "$env_src" "$REMOTE_SSH:/tmp/"
    fi
    remote_run "install -m 755 /tmp/start-ncc-api.sh $(printf '%q' "$api_dir")/start-ncc-api.sh && install -m 644 /tmp/lvqian-erp-crash.env $(printf '%q' "$api_dir")/lvqian-erp-crash.env && install -m 755 /tmp/start-ncc-api.sh /usr/local/share/lvqian-erp/start-ncc-api.sh && install -m 644 /tmp/lvqian-erp-crash.env /usr/local/share/lvqian-erp/lvqian-erp-crash.env && rm -f /tmp/start-ncc-api.sh /tmp/lvqian-erp-crash.env"
  fi
  ok "已下发 crash dump 启动脚本(start-ncc-api.sh / lvqian-erp-crash.env)"
}

# 同步后写入手机端日报 H5(仓库「绿纤日报/」→ wwwroot/html/;不含 bak/副本)
ensure_prod_html_assets() {
  local api_dir="$1"
  local src_dir="$ROOT/绿纤日报"
  local dest_rel="wwwroot/html"
  [ -d "$src_dir" ] || {
    warn "缺少 $src_dir,跳过日报 H5 下发"
    return 0
  }
  [ -f "$src_dir/dailyReport.html" ] || {
    warn "缺少 $src_dir/dailyReport.html,跳过日报 H5 下发"
    return 0
  }
  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] 将下发日报 H5(源: 绿纤日报/)→ $api_dir/$dest_rel"
    return 0
  fi
  # 排除备份/副本,避免把 bak 推到正式 wwwroot/html
  local -a html_excludes=(
    --exclude='*.bak*'
    --exclude='*_副本*'
    --exclude='*.bak'
    --exclude='.DS_Store'
  )
  if [ "$DEPLOY_MODE" = "local" ]; then
    mkdir -p "$api_dir/$dest_rel"
    rsync -a "${html_excludes[@]}" "$src_dir"/ "$api_dir/$dest_rel"/
  else
    remote_run "mkdir -p $(printf '%q' "$api_dir/$dest_rel")"
    rsync -a "${html_excludes[@]}" -e "$RSYNC_RSH" "$src_dir"/ "$REMOTE_SSH:$api_dir/$dest_rel"/
  fi
  ok "已下发手机端日报 H5(源: 绿纤日报/ → wwwroot/html/)"
}

# 同步前 dry-run:若输出里出现受保护文件名,立即中止(防止 exclude 失效)
assert_rsync_will_not_touch_protected() {
  local src="$1"
  local dst_display="$2"
  local preview
  preview="$3"
  if printf '%s\n' "$preview" | grep -Eiq '(^|/| )(appsettings(\.[^/]+)?\.json|web\.config|nlog(\.[^/]+)?\.config)($| |\t)'; then
    err "rsync 预检发现将触及受保护配置文件,已中止!目标: $dst_display"
    err "预检片段:"
    printf '%s\n' "$preview" | grep -Ei '(appsettings|web\.config|nlog)' >&2 || true
    die "请检查 RSYNC_EXCLUDES / 暂存目录清理逻辑"
  fi
  ok "rsync 预检通过:不会推送/覆盖受保护配置 → $dst_display"
}

sync_dir_local() {
  local src="$1"
  local dst="$2"
  local label="$3"
  local with_delete="${4:-1}"
  [ -d "$src" ] || die "源目录不存在: $src"
  mkdir -p "$dst"
  local del_flag=()
  [ "$with_delete" = "1" ] && del_flag=(--delete)

  local preview
  preview="$(rsync -a --dry-run -i "${del_flag[@]}" "${RSYNC_EXCLUDES[@]}" "$src"/ "$dst"/ 2>&1 || true)"
  assert_rsync_will_not_touch_protected "$src" "$dst" "$preview"

  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] rsync → $dst  ($label)"
    printf '%s\n' "$preview" | head -n 40
  else
    log "同步 $label → $dst"
    rsync -a "${del_flag[@]}" "${RSYNC_EXCLUDES[@]}" "$src"/ "$dst"/
  fi
}

sync_dir_remote() {
  local src="$1"
  local dst="$2"
  local label="$3"
  local with_delete="${4:-1}"
  [ -d "$src" ] || die "源目录不存在: $src"
  local dest="$REMOTE_SSH:$dst"
  local del_flag=()
  [ "$with_delete" = "1" ] && del_flag=(--delete)

  local preview
  # shellcheck disable=SC2086
  preview="$(rsync -a --dry-run -i "${del_flag[@]}" "${RSYNC_EXCLUDES[@]}" -e "$RSYNC_RSH" "$src"/ "$dest"/ 2>&1 || true)"
  assert_rsync_will_not_touch_protected "$src" "$dest" "$preview"

  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] rsync → $dest  ($label)"
    printf '%s\n' "$preview" | head -n 40
  else
    log "同步 $label → $dest"
    rsync -a "${del_flag[@]}" "${RSYNC_EXCLUDES[@]}" -e "$RSYNC_RSH" "$src"/ "$dest"/
  fi
}

# 后台只更新 wwwroot/index.html 与 wwwroot/admin/,绝不 --delete 整个 wwwroot(避免清掉上传文件)
sync_admin_wwwroot_local() {
  local src="$STAGING/admin-wwwroot"
  local dst="$1"
  mkdir -p "$dst/admin"
  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] 更新 $dst/index.html 与 $dst/admin/"
    rsync -a --dry-run "$src/index.html" "$dst/index.html"
    rsync -a --dry-run --delete "$src/admin"/ "$dst/admin"/
  else
    log "同步管理后台 → $dst (仅 index.html + admin/)"
    rsync -a "$src/index.html" "$dst/index.html"
    rsync -a --delete "$src/admin"/ "$dst/admin"/
  fi
}

sync_admin_wwwroot_remote() {
  local src="$STAGING/admin-wwwroot"
  local dst="$1"
  local dest="$REMOTE_SSH:$dst"
  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] 更新 $dest/index.html 与 $dest/admin/"
    # shellcheck disable=SC2086
    rsync -a --dry-run -e "$RSYNC_RSH" "$src/index.html" "$dest/index.html"
    rsync -a --dry-run --delete -e "$RSYNC_RSH" "$src/admin"/ "$dest/admin"/
  else
    log "同步管理后台 → $dest (仅 index.html + admin/)"
    remote_run "mkdir -p $(printf '%q' "$dst/admin")"
    rsync -a -e "$RSYNC_RSH" "$src/index.html" "$dest/index.html"
    rsync -a --delete -e "$RSYNC_RSH" "$src/admin"/ "$dest/admin"/
  fi
}

build_api() {
  log "-------- 构建接口 (dotnet publish Release) --------"
  command -v dotnet >/dev/null 2>&1 || die "未找到 dotnet"
  rm -rf "$STAGING/api"
  mkdir -p "$STAGING/api"
  dotnet publish "$API_PROJECT" -c Release -o "$STAGING/api" --nologo

  # 第一层保护:从待同步产物中删掉全部受保护配置(任意深度),残留则中止
  strip_protected_configs_from_staging "$STAGING/api"
  ok "接口发布完成,暂存目录已清除全部受保护配置文件"
}

# 正式站 publicPath=admin/:wwwroot/index.html + wwwroot/admin/{static,cdn,h5,...}
pack_admin_for_prod() {
  local dist="$ADMIN_DIR/dist"
  local pack="$STAGING/admin-wwwroot"
  [ -f "$dist/index.html" ] || die "缺少管理后台产物: $dist/index.html"

  rm -rf "$pack"
  mkdir -p "$pack/admin"
  cp "$dist/index.html" "$pack/index.html"

  # dist 根下除 index.html 外的内容,全部放进 admin/,匹配 HTML 里的 admin/static/...
  local item
  for item in "$dist"/*; do
    [ -e "$item" ] || continue
    local base
    base="$(basename "$item")"
    if [ "$base" = "index.html" ]; then
      continue
    fi
    cp -R "$item" "$pack/admin/"
  done

  [ -d "$pack/admin/static" ] || die "打包失败:未找到 admin/static(请检查 vue publicPath 与 dist 结构)"
  ok "管理后台已整理为正式目录结构 → $pack (index.html + admin/)"
}

build_admin() {
  log "-------- 构建管理后台 --------"
  load_nvm
  cd "$ADMIN_DIR"
  if [ ! -d node_modules ]; then
    warn "未检测到 node_modules,执行 npm install…"
    npm install
  fi

  if [ "$ADMIN_BUILD_WITH_H5" = "1" ]; then
    npm run build:with-h5
  else
    if [ ! -f "$H5_INDEX" ]; then
      die "管理后台生产构建需要 H5 产物: $H5_INDEX
可选:
  1) 在 HBuilderX 发行 Web 后重试
  2) 设置 ADMIN_BUILD_WITH_H5=1 使用本机 HBuilderX CLI
  3) 已有完整 dist 时用: ./deploy.prod.sh --skip-build --admin-only"
    fi
    npm run build
  fi
  [ -f "$ADMIN_DIR/dist/index.html" ] || die "管理后台构建失败:缺少 dist/index.html"
  ok "管理后台构建完成 → $ADMIN_DIR/dist"
  cd "$ROOT"
  pack_admin_for_prod
}

# 对齐 Antis.Erp.Plat:按 cwd 只停正式目录进程,再 nohup 拉起(不动测试环境)
restart_api_if_needed() {
  local custom="${PROD_API_RESTART_CMD:-}"
  local auto="${PROD_API_RESTART:-1}"
  local api_dir="$TARGET_API"
  local port="${PROD_API_PORT:-2013}"
  local dotnet_bin="${PROD_DOTNET:-/www/server/dotnet/6.0.417/dotnet}"
  local stamp
  stamp="$(date +%Y%m%d%H%M%S)"

  if [ "$DRY_RUN" = "1" ]; then
    log "[dry-run] 将重启正式 API:$api_dir 端口 $port"
    return 0
  fi

  if [ -n "$custom" ]; then
    log "重启正式接口(自定义命令)…"
    if [ "$DEPLOY_MODE" = "remote" ]; then
      remote_run "$custom"
    else
      bash -lc "$custom"
    fi
    ok "自定义重启命令已执行"
    return 0
  fi

  if [ "$auto" != "1" ]; then
    warn "PROD_API_RESTART=0,跳过自动重启;请到宝塔手动启动「绿纤ERP_生产环境」"
    return 0
  fi

  log "重启正式 API(仅 cwd=${api_dir},端口 ${port};带 crash dump 环境;不动测试环境)…"
  mkdir -p "$STAGING"
  local restart_sh="$STAGING/restart-prod-api-${stamp}.sh"
  cat >"$restart_sh" <<EOS
#!/bin/bash
set -euo pipefail
DIR='$api_dir'
REAL=\$(readlink -f "\$DIR" 2>/dev/null || echo "\$DIR")
PORT='$port'
DOTNET='$dotnet_bin'
BT_PID_DIR=/var/tmp/net_project
BT_NAME='绿纤ERP_生产环境'
cd "\$DIR"
mkdir -p logs /www/wwwlogs/lvqian_erp_crash "\$BT_PID_DIR"
chmod 777 "\$BT_PID_DIR" 2>/dev/null || true

killed=0
for pid in \$(pgrep -f 'NCC.API.dll' || true); do
  cwd=\$(readlink "/proc/\$pid/cwd" 2>/dev/null || true)
  if [[ "\$cwd" == "\$DIR" || "\$cwd" == "\$REAL" ]]; then
    echo "stop pid=\$pid cwd=\$cwd"
    kill "\$pid" || true
    killed=1
  fi
done

if [[ "\$killed" -eq 1 ]]; then
  for i in \$(seq 1 15); do
    sleep 1
    still=0
    for pid in \$(pgrep -f 'NCC.API.dll' || true); do
      cwd=\$(readlink "/proc/\$pid/cwd" 2>/dev/null || true)
      if [[ "\$cwd" == "\$DIR" || "\$cwd" == "\$REAL" ]]; then
        still=1
      fi
    done
    [[ "\$still" -eq 0 ]] && break
    if [[ "\$i" -eq 10 ]]; then
      for pid in \$(pgrep -f 'NCC.API.dll' || true); do
        cwd=\$(readlink "/proc/\$pid/cwd" 2>/dev/null || true)
        if [[ "\$cwd" == "\$DIR" || "\$cwd" == "\$REAL" ]]; then
          kill -9 "\$pid" || true
        fi
      done
    fi
  done
fi

# 优先走启动脚本(含托管 dump);否则 source env 后直接拉起
if [ -x "\$DIR/start-ncc-api.sh" ]; then
  nohup env PROD_DOTNET="\$DOTNET" PROD_API_PORT="\$PORT" APP_DIR="\$DIR" "\$DIR/start-ncc-api.sh" >> logs/console.log 2>&1 &
else
  if [ -f "\$DIR/lvqian-erp-crash.env" ]; then
    set -a
    # shellcheck disable=SC1091
    . "\$DIR/lvqian-erp-crash.env"
    set +a
  fi
  ulimit -c unlimited || true
  nohup "\$DOTNET" NCC.API.dll urls=http://localhost:\${PORT} >> logs/console.log 2>&1 &
fi
NEWPID=\$!
echo "\$NEWPID" > "\$BT_PID_DIR/\${BT_NAME}.pid"
chmod 666 "\$BT_PID_DIR/\${BT_NAME}.pid" 2>/dev/null || true
echo "started pid=\$NEWPID port=\$PORT cwd=\$DIR bt_pid_file=\$BT_PID_DIR/\${BT_NAME}.pid"
sleep 4
if ss -lntp 2>/dev/null | grep -q ":\$PORT "; then
  echo LISTEN_OK
elif pgrep -af 'NCC.API.dll' | grep -q "\$PORT"; then
  echo PROCESS_OK
else
  echo '启动失败,最近日志:'
  tail -n 80 logs/console.log || true
  exit 1
fi
# 校验托管 dump 环境已注入
if tr '\\0' '\\n' < /proc/\$NEWPID/environ 2>/dev/null | grep -q 'DOTNET_DbgEnableMiniDump=1'; then
  echo DUMP_ENV_OK
else
  echo DUMP_ENV_MISSING
fi
pgrep -af 'NCC.API.dll' | grep -F 'Lvqian_erp_test' && echo TEST_ENV_ALIVE || echo TEST_ENV_NOT_RUNNING
EOS
  chmod +x "$restart_sh"

  if [ "$DEPLOY_MODE" = "remote" ]; then
    local remote_sh="/tmp/lvqian-restart-prod-${stamp}.sh"
    # 正式机未必有 rsync,上传脚本统一用 scp
    if [ "${SSH_WRAPPER:-}" = "sshpass" ]; then
      sshpass -e scp -o StrictHostKeyChecking=accept-new "$restart_sh" "$REMOTE_SSH:$remote_sh"
    elif [ "${SSH_WRAPPER:-}" = "expect" ]; then
      # expect 包装的是 ssh;scp 用同密码环境变量临时走 sshpass/expect 管道较复杂,改为 base64 远程写入
      local b64
      b64="$(base64 <"$restart_sh" | tr -d '\n')"
      remote_run "echo '$b64' | base64 -d > $(printf '%q' "$remote_sh") && chmod +x $(printf '%q' "$remote_sh")"
    else
      scp -o StrictHostKeyChecking=accept-new -o BatchMode=yes "$restart_sh" "$REMOTE_SSH:$remote_sh"
    fi
    remote_run "bash $(printf '%q' "$remote_sh") && rm -f $(printf '%q' "$remote_sh")"
  else
    bash "$restart_sh"
  fi
  rm -f "$restart_sh"
  ok "正式 API 已重启(:${port})"
}

# ---------- 主流程 ----------
resolve_targets

log "======== 绿纤 ERP 正式环境部署 ========"
log "模式: $DEPLOY_MODE"
log "配置: $ENV_FILE"
[ "$DO_API" = "1" ] && log "接口目标: ${TARGET_API}${REMOTE_SSH:+ (@$REMOTE_SSH)}"
[ "$DO_ADMIN" = "1" ] && log "后台目标: ${TARGET_ADMIN}${REMOTE_SSH:+ (@$REMOTE_SSH)}"
if [ "$SKIP_BUILD" = "0" ]; then
  log "流程: ①本地构建最新 → ②打包整理 → ③同步正式机 → ④重启 API"
else
  warn "流程: 跳过构建(--skip-build),仅用已有产物同步(一键部署入口不会走这条)"
fi
[ "$DRY_RUN" = "1" ] && warn "DRY-RUN:不会写入正式目录"
log "★ 保护规则:永不覆盖正式环境 appsettings.json(及 appsettings.*.json)"
log "======================================"

if [ "$ASSUME_YES" != "1" ] && [ "$DRY_RUN" != "1" ]; then
  printf '确认部署到正式环境?输入 y 或 yes 继续: '
  read -r ans
  case "$(printf '%s' "$ans" | tr '[:upper:]' '[:lower:]')" in
    y|yes) ;;
    *) die "已取消(需输入 y 或 yes)" ;;
  esac
fi

# 部署前:备份正式配置 + 记录指纹
init_config_hash_store
if [ "$DO_API" = "1" ]; then
  if [ "$DEPLOY_MODE" = "local" ]; then
    [ -d "$TARGET_API" ] || die "正式接口目录不存在: $TARGET_API"
    backup_protected_configs_local "$TARGET_API"
  else
    backup_protected_configs_remote "$TARGET_API"
  fi
fi

if [ "$SKIP_BUILD" = "0" ]; then
  if [ "$DO_API" = "1" ]; then
    build_api
  fi
  if [ "$DO_ADMIN" = "1" ]; then
    build_admin
  fi
else
  warn "已跳过构建 (--skip-build)"
  if [ "$DO_API" = "1" ]; then
    [ -d "$STAGING/api" ] || die "无暂存接口产物,请先不带 --skip-build 构建一次"
  fi
  if [ "$DO_ADMIN" = "1" ]; then
    [ -f "$ADMIN_DIR/dist/index.html" ] || die "无管理后台 dist,请先构建"
    pack_admin_for_prod
  fi
fi

# 同步
if [ "$DO_API" = "1" ]; then
  # 同步前再次确保暂存无受保护配置(含 --skip-build)
  strip_protected_configs_from_staging "$STAGING/api"
  if [ "$DEPLOY_MODE" = "local" ]; then
    sync_dir_local "$STAGING/api" "$TARGET_API" "接口"
    verify_protected_configs_unchanged_local "$TARGET_API"
  else
    sync_dir_remote "$STAGING/api" "$TARGET_API" "接口"
    verify_protected_configs_unchanged_remote "$TARGET_API"
  fi
  # rsync --delete 不会再删运维脚本/日报 H5;此处主动下发/刷新(日报源=绿纤日报/)
  ensure_prod_crash_scripts "$TARGET_API"
  ensure_prod_html_assets "$TARGET_API"
fi

if [ "$DO_ADMIN" = "1" ]; then
  if [ "$DEPLOY_MODE" = "local" ]; then
    [ -d "$TARGET_ADMIN" ] || mkdir -p "$TARGET_ADMIN"
    sync_admin_wwwroot_local "$TARGET_ADMIN"
  else
    sync_admin_wwwroot_remote "$TARGET_ADMIN"
  fi
  ok "管理后台已同步到正式 wwwroot(仅 index.html + admin/,不影响上传目录)"
fi

if [ "$DO_API" = "1" ]; then
  restart_api_if_needed
fi

ok "正式环境部署完成"
log "提醒:若未自动重启,请手动重启正式接口进程后再验收。"