name: Release

permissions:
  actions: read
  contents: write
  packages: write

on:
  push:
    tags:
      # so a vX.Y.Z-test1 doesn't trigger build
      - 'v[0-9]+.[0-9]+.[0-9]+'
      - 'v[0-9]+.[0-9]+.[0-9]+-pre*'

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # pin@v3

      - name: Set up QEMU
        uses: docker/setup-qemu-action@68827325e0b33c7199eb31dd4e31fbe9023e06e3 # pin@v2

      - name: Set up Docker Buildx
        id: buildx
        uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # pin@v2

      - name: Available platforms
        run: echo ${{ steps.buildx.outputs.platforms }}

      - name: Log in to Docker Hub
        uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # pin@v2
        with:
          username: ${{ secrets.DOCKER_USER }}
          password: ${{ secrets.DOCKER_TOKEN }}

      - name: Build
        id: build
        run: |
          make info
          make release
          VERSION=$(make echo-version)
          echo "VERSION=${VERSION}" >> $GITHUB_ENV
          PACKAGE_VERSION=$(make echo-package-version)
          echo "Version $VERSION, Package version $PACKAGE_VERSION"

      - name: Build and push Docker image
        uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # pin@v3
        with:
          context: .
          platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x
          push: true
          tags: fortio/fortio:${{ env.VERSION }}, fortio/fortio:latest

      - name: Create Release
        id: create_release
        # Need to find a replacement not using set-output
        uses: actions/create-release@0cb9c9b65d5d1901c1f53e5e66eaf4afd303e70e # pin@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
        with:
          tag_name: ${{ github.ref }}
          release_name: Fortio ${{ env.VERSION }}
          draft: true

      - name: Upload release artifacts
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          tag_name="${GITHUB_REF##*/}"
          echo "will use tag_name=$tag_name"
          # tends to fail and not find the release somehow; add a small sleep... (yuck)
          sleep 10
          gh release upload "${tag_name}" release/*.{tgz,zip,rpm,deb,gz}
