name: Release Pipeline

on:
  release:
    types: [ created ]
  push:
    branches: [ main ]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Custom tag name for the image'
        required: true
        type: string
      ref:
        description: 'Git ref to checkout (branch, tag, or SHA)'
        required: true
        default: 'main'
        type: string

env:
  IMAGE_NAME: wygiwyh

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.ref }}
        if: github.event_name == 'workflow_dispatch'

      - name: Checkout code (non-manual)
        uses: actions/checkout@v4
        if: github.event_name != 'workflow_dispatch'

      - name: Log in to Docker Hub
        uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Build and push nightly image
        if: github.event_name == 'push'
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/prod/django/Dockerfile
          push: true
          provenance: false
          build-args: |
            VERSION=nightly
          tags: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}:nightly
          platforms: linux/amd64,linux/arm64
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Build and push release image
        if: github.event_name == 'release'
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/prod/django/Dockerfile
          push: true
          provenance: false
          build-args: |
            VERSION=${{ github.event.release.tag_name }}
          tags: |
            ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}:latest
            ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}:${{ github.event.release.tag_name }}
          platforms: linux/amd64,linux/arm64
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Build and push custom image
        if: github.event_name == 'workflow_dispatch'
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/prod/django/Dockerfile
          push: true
          provenance: false
          build-args: |
            VERSION=${{ github.event.inputs.tag }}
          tags: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}:${{ github.event.inputs.tag }}
          platforms: linux/amd64,linux/arm64
          cache-from: type=gha
          cache-to: type=gha,mode=max
