name: Release Image

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      image_tag:
        description: Optional tag override, defaults to sha-<commit>
        required: false
        type: string

permissions:
  contents: read
  packages: write

jobs:
  build-and-push:
    name: Build And Push Images
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: vars
        name: Compute image refs
        run: |
          owner="$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')"
          repo="$(basename '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')"
          image_tag="${{ inputs.image_tag }}"
          if [ -z "${image_tag}" ]; then
            image_tag="sha-${GITHUB_SHA}"
          fi
          echo "app_image=ghcr.io/${owner}/${repo}-app:${image_tag}" >> "$GITHUB_OUTPUT"
          echo "migrator_image=ghcr.io/${owner}/${repo}-migrator:${image_tag}" >> "$GITHUB_OUTPUT"

      - name: Build and push app image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile.prod
          target: runner
          push: true
          tags: ${{ steps.vars.outputs.app_image }}
          cache-from: type=gha,scope=app-image
          cache-to: type=gha,mode=max,scope=app-image

      - name: Build and push migrator image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./Dockerfile.prod
          target: migrator
          push: true
          tags: ${{ steps.vars.outputs.migrator_image }}
          cache-from: type=gha,scope=migrator-image
          cache-to: type=gha,mode=max,scope=migrator-image

      - name: Publish release summary
        run: |
          {
            echo "## Image release"
            echo
            echo "- App image: \`${{ steps.vars.outputs.app_image }}\`"
            echo "- Migrator image: \`${{ steps.vars.outputs.migrator_image }}\`"
          } >> "$GITHUB_STEP_SUMMARY"
