#!/bin/bash

# 远程服务器配置
REMOTE_HOST="192.168.0.95"
REMOTE_USER="root"
REMOTE_PASSWORD="aiotagro"
REMOTE_DIR="/data/java/aiotmini"

# 本地项目配置
PROJECT_DIR=$(pwd)
SERVER_MODULE="aagro-server"
TARGET_JAR="${SERVER_MODULE}/target/${SERVER_MODULE}.jar"

echo "开始部署项目到远程服务器..."

# 1. 清理并构建项目
echo "正在清理并构建项目..."
mvn clean package -Dmaven.test.skip=true

if [ $? -ne 0 ]; then
    echo "项目构建失败，退出部署"
    exit 1
fi

echo "项目构建成功"

# 2. 检查目标jar文件是否存在
if [ ! -f "${TARGET_JAR}" ]; then
    echo "目标jar文件不存在: ${TARGET_JAR}"
    exit 1
fi

# 3. 上传到远程服务器
echo "正在上传文件到远程服务器..."
scp ${TARGET_JAR} ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/

if [ $? -ne 0 ]; then
    echo "文件上传失败"
    exit 1
fi

echo "文件上传成功"

# 4. 上传Dockerfile到远程服务器
echo "正在上传Dockerfile到远程服务器..."
scp ${SERVER_MODULE}/Dockerfile ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/

if [ $? -ne 0 ]; then
    echo "Dockerfile上传失败"
    exit 1
fi

echo "Dockerfile上传成功"

# 5. 在远程服务器上构建Docker镜像并运行容器
echo "正在远程服务器上构建Docker镜像并运行容器..."
ssh ${REMOTE_USER}@${REMOTE_HOST} "
    cd ${REMOTE_DIR} && \
    docker build -t aagro-server . && \
    docker stop aagro-server-container 2>/dev/null && \
    docker rm aagro-server-container 2>/dev/null && \
    docker run -d \
      --name aagro-server-container \
      --restart always \
      -p 48080:48080 \
      -e SPRING_PROFILES_ACTIVE=custom \
      aagro-server
"

if [ $? -ne 0 ]; then
    echo "远程Docker操作失败"
    exit 1
fi

echo "项目部署成功！"
echo "访问地址: http://${REMOTE_HOST}:48080"