---
name: Tag a release

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Tag to apply, in the form "v0.0.0" or leave blank to automatically bump the version'
        required: false

jobs:
  tag-release:
    name: Given the tag input value, check the value, update the version number of the application, commit, tag, push tag
    runs-on: ubuntu-latest

    permissions:
      actions: write
      contents: write

    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install git-cliff
        uses: taiki-e/install-action@git-cliff

      - name: Check the version number from input
        env:
          INPUT_VERSION: ${{ github.event.inputs.version }}
        run: |
          echo "Validating that tag is in the correct format v0.0.1"
          if [ -z "${INPUT_VERSION}" ]; then
              input_version=$(git-cliff --bumped-version)
          else
              input_version="${INPUT_VERSION}"
          fi
          if grep -P '^v[0-9]+\.[0-9]+\.[0-9]+' <<< "${input_version}"; then
              echo "tag=${input_version}" >> $GITHUB_ENV
              echo "cargo_version=version = \"${input_version:1}\"" >> $GITHUB_ENV
          elif grep -P '^[0-9]+\.[0-9]+\.[0-9]+' <<< "${input_version}"; then
              echo "tag=v${input_version}" >> $GITHUB_ENV
              echo "cargo_version=version = \"${input_version}\"" >> $GITHUB_ENV
          else
              false
          fi

      - name: Setup GPG
        run: |
          echo "${{ secrets.SIGNINGKEY }}" | gpg --import

      - name: Setup git config
        run: |
          git config user.name "Tag Bot"
          git config user.email "github@noser.net"
          git config commit.gpgsign true
          git config user.signingkey ${{ secrets.SIGNINGKEYHASH }}

      - name: Replace the version number in Cargo.toml
        run: |
          sed -i 's/^version = .*/'"$cargo_version"'/g' Cargo.toml

      - name: Add, push, tag, push
        run: |
          git add .
          git commit -S -m "Release $tag"
          git push -f
          git tag $tag -s -m "Release $tag"
          git push origin $tag -f

      - name: Release Tag Repository Dispatch
        uses: benc-uk/workflow-dispatch@v1
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          repo: ${{env.GITHUB_REPOSITORY}}
          ref: refs/tags/${{ env.tag }}
          workflow: release.yml
