name: 手动 AiDA back-java 开发分支构建部署
on:
  workflow_dispatch:

jobs:
  build_and_deploy:
    runs-on: ubuntu-latest
    outputs:
      build_status: ${{ job.status }}
      build_url: ${{ gitea.server_url }}/${{ gitea.repository.owner.name }}/${{ gitea.repository.name }}/actions/runs/${{ gitea.run_id }}

    permissions:
      contents: read
      packages: write

    env:
      REMOTE_DEPLOY_PATH: /workspace/workspace_aida/DevelopVersion/develop-version-aida-back

    steps:
      - name: 0.记录开始时间
        id: build_start_time
        run: echo "current_time=$(TZ='Asia/Hong_Kong' date '+%Y-%m-%d %H:%M:%S %Z')" >> $GITHUB_OUTPUT

      - name: 1.检出代码
        uses: actions/checkout@v4
        with:
          ref: dev/3.1_release_merge

      - name: 2.Set up JDK 21
        uses: actions/setup-java@v5
        with:
          java-version: '21'
          distribution: 'temurin'

      - name: 3.设置JAVA Maven 环境
        run: |
          # 适配root/普通用户
          SUDO=""
          [ "$(id -u)" != "0" ] && SUDO="sudo"

          # 安装依赖
          $SUDO apt update && $SUDO apt install -y wget tar --no-install-recommends

          # 下载Maven
          MAVEN_VERSION="3.9.11"
          MAVEN_TAR="apache-maven-${MAVEN_VERSION}-bin.tar.gz"
          MAVEN_URL="https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/${MAVEN_TAR}"
          wget --no-verbose -O /tmp/${MAVEN_TAR} ${MAVEN_URL}

          # 解压+软链接
          $SUDO tar -xzf /tmp/${MAVEN_TAR} -C /usr/local/
          $SUDO ln -sf /usr/local/apache-maven-${MAVEN_VERSION} /usr/local/maven

          # 配置PATH
          echo "/usr/local/maven/bin" >> $GITHUB_PATH
          export PATH="/usr/local/maven/bin:$PATH"

          # 验证
          mvn -v 

      - name: 4.构建jar包
        run: |
          echo "===== 开始构建JAR包 ====="
              # 新增：打印当前构建分支（两种方式双重确认）
          echo "当前工作目录分支：$(git branch --show-current)"
          echo "Gitea检出分支:${{ github.ref_name }}"
          echo "预期构建分支:dev/3.1_release_merge"
          echo "========================"
          mvn -B clean install -DskipTests -Pdev 2>&1
          # 检查构建是否成功
          if [ $? -ne 0 ]; then
          echo "JAR包构建失败!"
          exit 1
          fi

      - name: 5.生成Dockerfile
        run: |
          echo "===== 生成Dockerfile ====="
          cat > Dockerfile << 'EOF'
          FROM openjdk:21-ea-21-jdk-slim
          VOLUME /tmp
          RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
          RUN echo 'Asia/Shanghai' > /etc/timezone
          ADD ./aida-0.0.1-SNAPSHOT.jar /app.jar
          ENTRYPOINT ["java","-jar","/app.jar"]
          EOF
          echo "Dockerfile内容:"
          cat Dockerfile

      - name: 6.生成docker-compose.yml
        run: |
          echo "===== 生成docker-compose.yml ====="
          cat > docker-compose.yml << 'EOF'
          version: '3'
          services:
            aida_back:
              container_name: develop-version-aida-back
              build: .
              volumes:
                # 数据挂载
                - ./log:/log
              ports:
                - '10090:5567'
              restart: always
          EOF
          # 验证docker-compose.yml生成
          echo "docker-compose.yml内容:"
          cat docker-compose.yml

      - name: 7.安装SSH工具
        run: |
          $SUDO apt install -y sshpass openssh-client --no-install-recommends
          # 配置SSH免密
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H ${{ secrets.SERVER_HOST }} >> ~/.ssh/known_hosts

      - name: 8.同步文件到远程服务器
        run: |
          echo "===== 同步文件到远程服务器 ====="
          # 使用scp同步文件
          scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
            ./target/*.jar ./Dockerfile ./docker-compose.yml \
            ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}:${{ env.REMOTE_DEPLOY_PATH }} 2>&1

      - name: 9.部署和运行服务
        run: |
          echo "===== 开始部署服务 ====="
          # SSH执行部署命令
          ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
            ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }} << 'EOF_SSH'
            cd ${{ env.REMOTE_DEPLOY_PATH }}
            echo "停止旧容器..."
            docker compose down || true
            echo "清理Docker资源..."
            docker system prune -f
            echo "构建镜像..."
            docker compose build --no-cache
            echo "启动服务..."
            docker compose up -d
            echo "验证容器状态..."
            docker compose ps
            echo "部署完成！"
          EOF_SSH

      - name: 10.发送构建结果邮件
        if: always() # 无论上一步是否失败，都执行此步骤
        uses: dawidd6/action-send-mail@v3
        with:

          from: ${{ secrets.MAIL_USERNAME }}
          # --- 邮件配置 ---
          server_address: smtp.gmail.com # 替换为你的SMTP服务器地址
          server_port: 465 # 替换为你的SMTP端口 (通常是465或587)
          username: ${{ secrets.MAIL_USERNAME }} # 存储在Secrets中的邮箱用户名
          password: ${{ secrets.MAIL_PASSWORD }} # 存储在Secrets中的邮箱密码
          subject: 'Gitea Actions 构建通知: ${{ job.status }} - AiDA back-java Develop'
          # 收件人列表，可以根据需要更改
          to: 'cgzhou@aidlab.hk,zchengrong@yeah.net' # 替换为实际收件人邮箱

          # --- 邮件正文内容 ---
          body: |
            项目: AiDA back-java Develop
            分支: dev/3.1_release_merge

            🎉 构建结果: ${{ job.status }}

            📅 构建时间: ${{ steps.build_start_time.outputs.current_time }}

            🔗 构建链接: ${{ gitea.server_url }}/${{ gitea.repository.owner.name }}/${{ gitea.repository.name }}/actions/runs/${{ gitea.run_id }}

          # 确保邮件内容为纯文本，或者你可以设置为 html: true 并调整 body
          content_type: text/plain