name: Publish Nightly Docker Image

on:
  push:
    branches:
      - next/**
  workflow_dispatch:

env:
  DOCKERHUB_REGISTRY: docker.io
  GITHUB_REGISTRY: ghcr.io
  DOCKERHUB_IMAGE_NAME: ${{ secrets.DOCKER_USERNAME }}/${{ github.event.repository.name }}
  GITHUB_IMAGE_NAME: ${{ github.repository }}

concurrency:
  group: nightly-docker-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-and-push-nightly:
    name: Build and push nightly Docker images
    strategy:
      matrix:
        variant: [debian, alpine]
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write

    steps:
      - name: Check out the repo
        uses: actions/checkout@v4.2.2

      - name: Install cosign
        uses: sigstore/cosign-installer@v3.8.0
        with:
          cosign-release: v2.2.4

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3.3.0
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3.3.0
        with:
          registry: ${{ env.GITHUB_REGISTRY }}
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5.6.1
        with:
          images: |
            ${{ env.DOCKERHUB_IMAGE_NAME }}
            ${{ env.GITHUB_REGISTRY }}/${{ env.GITHUB_IMAGE_NAME }}
          tags: |
            type=raw,value=nightly,enable=${{ matrix.variant == 'debian' }}
            type=raw,value=nightly-alpine,enable=${{ matrix.variant == 'alpine' }}
            type=sha,format=short,prefix=nightly-,enable=${{ matrix.variant == 'debian' }}
            type=sha,format=short,prefix=nightly-alpine-,enable=${{ matrix.variant == 'alpine' }}

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

      - name: Build and push Docker image
        id: build-and-push
        uses: docker/build-push-action@v6.13.0
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            VARIANT=${{ matrix.variant }}
          platforms: linux/amd64,linux/arm64
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Sign the published Docker images
        env:
          TAGS: ${{ steps.meta.outputs.tags }}
          DIGEST: ${{ steps.build-and-push.outputs.digest }}
        run: |
          echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
