name: develop

on:
  push:
    branches: ["develop"]

jobs:
  build-and-push:
    name: Build and push to Aliyun ACR
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to Aliyun Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ vars.ALIYUN_REGISTRY }}
          username: ${{ vars.ALIYUN_USERNAME }}
          password: ${{ secrets.ALIYUN_PASSWORD }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest
            ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:${{ github.sha }}

  deploy:
    name: Deploy to server
    runs-on: ubuntu-latest
    needs: build-and-push # 等构建推送完成后再部署
    steps:
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.3
        with:
          host: ${{ vars.HOST }}
          username: ${{ vars.USERNAME }}
          key: ${{ secrets.SSH_KEY }}
          port: 22
          script: |
            # 登录阿里云镜像仓库
            docker login --username=${{ vars.ALIYUN_USERNAME }} --password=${{ secrets.ALIYUN_PASSWORD }} ${{ vars.ALIYUN_REGISTRY }}
            # 拉取最新镜像
            docker pull ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest
            # 停止并删除旧容器（如果存在）
            docker stop react-app 2>/dev/null || true
            docker rm react-app 2>/dev/null || true
            # 运行新容器
            docker run -d \
              --name react-app \
              --restart always \
              -p 8080:80 \
              ${{ vars.ALIYUN_REGISTRY }}/${{ vars.ALIYUN_NAMESPACE }}/${{ vars.ALIYUN_REPO }}:latest
            # 清理无用镜像
            docker image prune -f
