#!/bin/sh

set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd)
POM_FILE="$ROOT_DIR/ruoyi-admin/pom.xml"
DEPLOY_SH="$ROOT_DIR/deploy/deploy-to-nas.sh"
DEPLOY_PS1="$ROOT_DIR/deploy/deploy.ps1"
DOCKERFILE="$ROOT_DIR/docker/backend/Dockerfile"
TARGET_DIR="$ROOT_DIR/ruoyi-admin/target"

echo "[检查] 后端打包必须同时产出 jar 与 war，部署脚本只能使用 war"

if ! grep -Fq '<packaging>jar</packaging>' "$POM_FILE"; then
    echo "失败: ruoyi-admin 仍需保持 jar 打包类型以支持本地内嵌 Tomcat 运行"
    exit 1
fi

if ! grep -Fq '<goal>war</goal>' "$POM_FILE"; then
    echo "失败: 未显式执行 war 打包目标"
    exit 1
fi

if ! grep -Fq 'ruoyi-admin.war' "$DEPLOY_SH"; then
    echo "失败: deploy-to-nas.sh 未改为使用 ruoyi-admin.war"
    exit 1
fi

if grep -Fq 'ruoyi-admin.jar' "$DEPLOY_SH"; then
    echo "失败: deploy-to-nas.sh 仍引用 ruoyi-admin.jar"
    exit 1
fi

if ! grep -Fq 'ruoyi-admin.war' "$DEPLOY_PS1"; then
    echo "失败: deploy.ps1 未改为使用 ruoyi-admin.war"
    exit 1
fi

if grep -Fq 'ruoyi-admin.jar' "$DEPLOY_PS1"; then
    echo "失败: deploy.ps1 仍引用 ruoyi-admin.jar"
    exit 1
fi

if ! grep -Fq 'COPY backend/ruoyi-admin.war /app/ruoyi-admin.war' "$DOCKERFILE"; then
    echo "失败: Dockerfile 未改为复制 ruoyi-admin.war"
    exit 1
fi

if grep -Fq 'ruoyi-admin.jar' "$DOCKERFILE"; then
    echo "失败: Dockerfile 仍引用 ruoyi-admin.jar"
    exit 1
fi

echo "[检查] 执行 Maven 打包产物校验"
(
    cd "$ROOT_DIR"
    mvn -pl ruoyi-admin -am package -DskipTests
)

if [ ! -f "$TARGET_DIR/ruoyi-admin.jar" ]; then
    echo "失败: 未生成 $TARGET_DIR/ruoyi-admin.jar"
    exit 1
fi

if [ ! -f "$TARGET_DIR/ruoyi-admin.war" ]; then
    echo "失败: 未生成 $TARGET_DIR/ruoyi-admin.war"
    exit 1
fi

echo "通过"
