name: Build and Push API Image

on:
  push:
    branches:
      - 'main'
      - 'deploy/dev'
  release:
    types: [published]

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    if: github.event.pull_request.draft == false
    steps:
    - name: Set up QEMU
      uses: docker/setup-qemu-action@v2

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

    - name: Login to Docker Hub
      uses: docker/login-action@v2
      with:
        username: ${{ secrets.DOCKERHUB_USER }}
        password: ${{ secrets.DOCKERHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v4
      with:
        images: langgenius/dify-api
        tags: |
          type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/') }}
          type=ref,event=branch
          type=sha,enable=true,priority=100,prefix=,suffix=,format=long
          type=raw,value=${{ github.ref_name }},enable=${{ startsWith(github.ref, 'refs/tags/') }}

    - name: Build and push
      uses: docker/build-push-action@v4
      with:
        context: "{{defaultContext}}:api"
        platforms: ${{ startsWith(github.ref, 'refs/tags/') && 'linux/amd64,linux/arm64' || 'linux/amd64' }}
        build-args: |
          COMMIT_SHA=${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.revision'] }}
        push: true
        tags: ${{ steps.meta.outputs.tags }}
        labels: ${{ steps.meta.outputs.labels }}
        cache-from: type=gha
        cache-to: type=gha,mode=max

    - name: Deploy to server
      if: github.ref == 'refs/heads/deploy/dev'
      uses: appleboy/ssh-action@v0.1.8
      with:
        host: ${{ secrets.SSH_HOST }}
        username: ${{ secrets.SSH_USER }}
        key: ${{ secrets.SSH_PRIVATE_KEY }}
        script: |
          ${{ secrets.SSH_SCRIPT }}
