name: release
on:
  push:
    tags:
      - "*"
jobs:
  goreleaser:
    runs-on: ubuntu-latest

    permissions:
      contents: write
      deployments: write
      packages: write
      id-token: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Prepare
        id: prepare
        run: |
          # Get rid of v prefix.
          ref_name="${GITHUB_REF_NAME/v/}"
          echo "version=$ref_name" >> $GITHUB_ENV

          # Check if tag is a valid semver without any suffixes; it must not be a pre-release.
          if [[ "$ref_name" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
            echo "pre_release=false" >> $GITHUB_ENV
          fi
      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: "1.21"
      - name: Auth to GCP
        uses: google-github-actions/auth@v0
        with:
          credentials_json: ${{ secrets.GCP_SERVICE_ACCOUNT_KEY }}
          create_credentials_file: true
          export_environment_variables: true
      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}
      - name: Set up gcloud
        uses: google-github-actions/setup-gcloud@v0
      - name: Release notes
        run: |
          owner="${{ vars.RELEASE_OWNER || github.actor }}"
          go run ./cmd/release-notes/main.go -version "${GITHUB_REF_NAME}" -owner "$owner" > ${{ runner.temp }}/releasenotes
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v5
        with:
          distribution: goreleaser
          version: v1.15.2
          args: release --clean --release-notes=${{ runner.temp }}/releasenotes
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          HOMEBREW_TAP_GITHUB_TOKEN: ${{ secrets.HOMEBREW_TAP_GITHUB_TOKEN }}
          SCOOP_BUCKET_GITHUB_TOKEN: ${{ secrets.SCOOP_BUCKET_GITHUB_TOKEN }}
          GS_BUCKET: ${{ secrets.GS_BUCKET }}
      - name: Copy to latest
        if: env.pre_release == 'false'
        run: gsutil -m cp "gs://${{ secrets.GS_BUCKET }}/${{ env.version }}/*" gs://${{ secrets.GS_BUCKET }}/latest
      - name: Bump Homebrew Formula
        uses: mislav/bump-homebrew-formula-action@v3
        # skip prereleases
        if: ${{ !contains(github.ref, '-') }}
        with:
          formula-name: runme
        env:
          COMMITTER_TOKEN: ${{ secrets.COMMITTER_TOKEN }}
