name: Build and Push WEB 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-web
        tags: |
          type=raw,value=latest,enable={{is_default_branch}}
          type=ref,event=branch
          type=sha,enable=true,priority=100,prefix=,suffix=,format=long
          type=semver,pattern={{major}}.{{minor}}.{{patch}}
          type=semver,pattern={{major}}.{{minor}}
          type=semver,pattern={{major}}

    - name: Build and push
      uses: docker/build-push-action@v4
      with:
        context: "{{defaultContext}}:web"
        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 }}