name: Release-plz

on:
  push:
    branches: [master]
  workflow_dispatch:
  pull_request:
    types: [closed]

permissions:
  contents: write
  pull-requests: write

env:
  CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse

jobs:
  delete-old-branches:
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request' && startsWith(github.head_ref, 'release-plz-')
    steps:
      - uses: actions/create-github-app-token@v2
        id: app-token
        with:
          app-id: ${{ secrets.RELEASE_PLZ_APP_ID }}
          private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }}

      - name: Delete release-plz branch
        run: gh api --method DELETE repos/${{ github.repository }}/git/refs/heads/${{ github.head_ref }}
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token }}

  release-pr:
    runs-on: ubuntu-latest
    if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
    steps:
      - uses: actions/create-github-app-token@v2
        id: app-token
        with:
          app-id: ${{ secrets.RELEASE_PLZ_APP_ID }}
          private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }}

      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false
          token: ${{ steps.app-token.outputs.token }}

      - uses: dtolnay/rust-toolchain@stable

      - uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  release:
    runs-on: ubuntu-latest
    needs: release-pr
    if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
    steps:
      - uses: actions/create-github-app-token@v2
        id: app-token
        with:
          app-id: ${{ secrets.RELEASE_PLZ_APP_ID }}
          private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }}

      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false
          token: ${{ steps.app-token.outputs.token }}

      - uses: dtolnay/rust-toolchain@stable

      - uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
