#!/bin/bash

# QAUP 简化打包脚本
# 基于现有复杂方案，简化为一键打包

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

print_message() {
    echo -e "${1}${2}${NC}"
}

print_message $BLUE "=== QAUP 简化打包脚本 ==="

# 1. 构建应用
print_message $BLUE "构建应用..."
cd "$PROJECT_ROOT"
mvn clean package -DskipTests -q

# 2. 准备镜像版本（使用国内镜像加速器）
POSTGRES_IMAGE="m.daocloud.io/docker.io/postgis/postgis:17-3.5-alpine"
REDIS_IMAGE="m.daocloud.io/docker.io/library/redis:8.0-alpine"
OPENJDK_IMAGE="m.daocloud.io/docker.io/library/eclipse-temurin:17-jre"

print_message $BLUE "拉取基础镜像..."
docker pull $POSTGRES_IMAGE
docker pull $REDIS_IMAGE  
docker pull $OPENJDK_IMAGE

# 3. 导出镜像（只导出基础镜像，不需要构建自定义镜像）
print_message $BLUE "导出镜像..."
mkdir -p qaup-deploy
docker save $POSTGRES_IMAGE $REDIS_IMAGE $OPENJDK_IMAGE | gzip > qaup-deploy/images.tar.gz

# 5. 复制必要文件
print_message $BLUE "准备部署文件..."
cp qaup-admin/target/qaup-admin.jar qaup-deploy/app.jar
cp deploy/simple/docker-compose.yml qaup-deploy/
cp deploy/simple/config.yml qaup-deploy/

# 复制数据库相关文件
mkdir -p qaup-deploy/sql
cp deploy/docker/postgres/qaup_database_schema.sql qaup-deploy/sql/ 2>/dev/null || echo "⚠ 数据库架构文件不存在"
cp deploy/docker/postgres/export/initial_data_complete.sql qaup-deploy/sql/ 2>/dev/null || echo "⚠ 完整初始数据文件不存在"

# 创建数据库初始化脚本
./deploy/simple/create-init-sql.sh
cp deploy/simple/init.sql qaup-deploy/

cp deploy/simple/deploy.sh qaup-deploy/
cp deploy/simple/update.sh qaup-deploy/
cp deploy/simple/DeployGuide.md qaup-deploy/

# 6. 创建部署包
PACKAGE_NAME="qaup-deploy-$(date +%Y%m%d-%H%M%S).zip"
cd qaup-deploy && zip -r ../$PACKAGE_NAME . && cd ..

print_message $GREEN "✅ 打包完成: $PACKAGE_NAME"
print_message $BLUE "部署包大小: $(du -sh $PACKAGE_NAME | cut -f1)"

echo ""
echo "部署说明:"
echo "1. 将 $PACKAGE_NAME 传输到目标服务器"
echo "2. unzip $PACKAGE_NAME && cd qaup-deploy"
echo "3. ./deploy.sh"