name: Docker Release

on:
  workflow_dispatch:
    inputs:
      release:
        description: 'Release version'
        required: true

permissions:
  # Required to stop running workflows
  actions: write
  packages: write

jobs:
  build-docker-images:
    name: Build Docker Images
    runs-on: ubuntu-latest
    steps:
      -
        name: Cancel previous workflows
        uses: styfle/cancel-workflow-action@0.9.1
        with:
          access_token: ${{ secrets.GITHUB_TOKEN }}
      -
        name: Checkout
        uses: actions/checkout@v3
      -
        name: Set up QEMU
        uses: docker/setup-qemu-action@v1
      -
        name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1
      -
        name: Install Cosign
        uses: sigstore/cosign-installer@v2.1.0
      -
        name: Login to GHCR
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}
      -
        name: Docker meta
        id: meta
        uses: docker/metadata-action@v3
        with:
          images: |
            ghcr.io/elastic/harp
      -
        id: build-and-push
        name: Build and push
        uses: docker/build-push-action@v2
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          build-args: VERSION=${{ github.event.inputs.release }}
          tags: |
            ghcr.io/${{ github.repository }}:latest
            ghcr.io/${{ github.repository }}:v${{ github.event.inputs.release }}
          labels: ${{ steps.meta.outputs.labels }}
      -
        name: Create SBOM
        uses: anchore/sbom-action@v0
        with:
          image: ghcr.io/${{ github.repository }}@${{ steps.build-and-push.outputs.digest }}
          registry-username: ${{ github.actor }}
          registry-password: ${{ github.token }}
          artifact-name: sbom.spdx
          format: spdx
      -
        name: Sign image and add attestations
        run: |
          echo -n "${COSIGN_PASSWORD}" | \
          cosign sign --key <(echo -n "${COSIGN_KEY}") \
            -a "repo=${{ github.repository }}" \
            -a "workflow=${{ github.workflow }}" \
            -a "ref=${{ github.sha }}" \
            ghcr.io/${{ github.repository }}@${{ steps.build-and-push.outputs.digest }}
          cosign attach sbom --sbom sbom.spdx ghcr.io/${{ github.repository }}@${{ steps.build-and-push.outputs.digest }}
        env:
          COSIGN_KEY: ${{ secrets.COSIGN_KEY }}
          COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
      -
        name: Verify the signature
        run: |
          cosign verify --key build/artifact/cosign.pub ghcr.io/${{ github.repository }}@${{ steps.build-and-push.outputs.digest }}
