#!/bin/bash # 生产环境:清理老系统文件 + 数据库演示/遗留数据 # 用法: prod-cleanup-legacy.sh [SQL_FILE] [CLEANUP_SH] [--yes] # --yes 跳过交互确认(供自动化使用) set -euo pipefail APP=/opt/ai-fresh-delivery SERVER="$APP/server" SKIP_CONFIRM=0 POSITIONAL=() for arg in "$@"; do if [ "$arg" = "--yes" ]; then SKIP_CONFIRM=1 else POSITIONAL+=("$arg") fi done SQL_FILE="${POSITIONAL[0]:-$HOME/prod-cleanup-legacy-data.sql}" echo "===== 1/4 清理数据库老数据 =====" if [ ! -f "$SQL_FILE" ]; then echo "Missing SQL file: $SQL_FILE" exit 1 fi cd "$SERVER" DB=$(grep -m1 '^DATABASE_URL=' .env | cut -d= -f2-) export PGPASSWORD PGPASSWORD=$(node -e "const u=new URL(process.argv[1]); console.log(decodeURIComponent(u.password||''))" "$DB") DB_MASKED=$(node -e "const u=new URL(process.argv[1]); if (u.password) u.password='***'; console.log(u.toString())" "$DB") echo "" echo "!!! 危险操作:将清空数十张业务表(orders/customers/skus/... 仅保留 superadmin 与系统配置)" echo " 目标数据库: $DB_MASKED" echo " SQL 文件: $SQL_FILE" echo " 同时会删除服务器上的老系统目录 (/opt/canteen 等)" if [ "$SKIP_CONFIRM" -ne 1 ]; then printf '确认继续请输入 YES: ' read -r CONFIRM if [ "$CONFIRM" != "YES" ]; then echo "已取消。" exit 1 fi fi CLEANUP_SH="${POSITIONAL[1]:-$HOME/prod-cleanup-legacy-data.sh}" if [ -f "$CLEANUP_SH" ]; then # 本脚本已确认过,向内层清库脚本传 --yes 避免重复确认 bash "$CLEANUP_SH" --yes else psql "$DB" -v ON_ERROR_STOP=1 -f "$SQL_FILE" fi echo "===== 2/4 禁止 migrate 自动灌演示数据 =====" if grep -q '^SKIP_DEMO_SEED=' .env 2>/dev/null; then sed -i 's/^SKIP_DEMO_SEED=.*/SKIP_DEMO_SEED=1/' .env else echo 'SKIP_DEMO_SEED=1' >> .env fi echo "===== 3/4 清理服务器上的老系统目录/文件 =====" # 旧 Python 后端 + 旧前端包 if [ -d /opt/canteen ]; then echo "Removing /opt/canteen (legacy backend)..." sudo rm -rf /opt/canteen fi # 前端静态目录中的废弃文件(test-h5 上执行时可忽略) if [ -d /opt/canteen-frontend ]; then rm -f /opt/canteen-frontend/92b103a63da586dfe02d.js \ /opt/canteen-frontend/bundle.js \ /opt/canteen-frontend/bundle.js.LICENSE.txt 2>/dev/null || true fi # 新系统仓库内的 Supabase Edge Functions 遗留 if [ -d "$APP/functions" ]; then echo "Removing $APP/functions ..." rm -rf "$APP/functions" fi # 清理 home 目录临时部署包(保留脚本由运维自行管理) rm -rf "$HOME/deploy-staging" 2>/dev/null || true echo "===== 4/4 数据核验 =====" psql "$DB" -c "SELECT 'users' AS item, count(*)::int AS cnt FROM auth.users UNION ALL SELECT 'orders', count(*)::int FROM orders UNION ALL SELECT 'customers', count(*)::int FROM customers UNION ALL SELECT 'skus', count(*)::int FROM skus UNION ALL SELECT 'branches', count(*)::int FROM branches;" echo "Cleanup complete. Only superadmin + system config/permissions/branches remain."