#!/usr/bin/env bash
# ============================================================
# 清理「路径错误的旧 zip」解压到网站根目录产生的扁平散落文件
# 用法：把本脚本放到网站根目录（与 index.php 同级），然后执行：
#        bash cleanup_badzip_residue.sh
# 说明：仅删除明确属于错误包的文件，不会动 index.php / PATCH-README*.txt
#       / app/ / install/ / public/ / config/ / storage/ 等正常文件。
# ============================================================
set -e

# 必须在网站根目录（存在 app/ 目录）运行，防止误删
if [ ! -d app ]; then
  echo "✗ 未在当前目录发现 app/ 目录，请在网站根目录运行本脚本"
  exit 1
fi

ROOT="$(pwd)"
echo "==> 网站根目录: $ROOT"

# 错误的扁平 PHP 文件（来自 app/Controllers、app/Core、app/Models、app/Views 被压扁）
FILES=(
  AdminController.php AuthController.php UpgradeController.php DashboardController.php
  ContactController.php OrderController.php MaterialsController.php ProductsController.php
  PurchasesController.php SalesController.php StockController.php StockHelper.php
  SuppliersController.php App.php Helper.php Installer.php Model.php
  DatabaseController.php UsersController.php NotificationsController.php OrdersController.php
  OutboundsController.php PurchaseOrdersController.php RemindersController.php ReportsController.php
  SalesOrdersController.php Notify.php Event.php Outbound.php OutboundItem.php
  PurchaseOrder.php PurchaseOrderItem.php SalesOrder.php SalesOrderItem.php
  dashboard.php login.php order_show.php orders.php system.php upgrade.php users.php
  contacts.php customers.php followups.php leads.php admin.php site.php subsys.php
  materials.php products.php purchases.php sales.php suppliers.php
  db_browse.php db_form.php db_tables.php notifications.php outbound_form.php
  outbound_print.php outbound_show.php outbounds.php purchase_order_form.php
  purchase_order_print.php purchase_order_show.php purchase_orders.php reminder_form.php
  reminders.php report_delivery.php report_po_detail.php report_so_po.php reports.php
  sales_order_form.php sales_order_print.php sales_order_show.php sales_orders.php
  user_form.php user_reset.php
)
# 错误包把 install/*.sql、public/* 也压扁到了根目录
FILES+=( schema.sql seed.php psi_orders.sql admin.css subsys.css admin.js robots.txt )

# 错误包产生的扁平目录
DIRS=( Subsys subsys upgrades )

DELETED=0
for f in "${FILES[@]}"; do
  if [ -f "$f" ]; then rm -f "$f"; echo "  删除文件 $f"; DELETED=$((DELETED+1)); fi
done
for d in "${DIRS[@]}"; do
  if [ -d "$d" ]; then rm -rf "$d"; echo "  删除目录 $d/"; DELETED=$((DELETED+1)); fi
done

echo ""
echo "✓ 清理完成，共删除 $DELETED 项。"
echo "  保留：index.php / PATCH-README*.txt / app/ / install/ / public/ / config/ / storage/ 等。"
echo "  建议随后用修正版 圣巧依_PSI升级包.zip 重新解压（路径已正确），并到后台执行数据库升级。"
