# This action assumes that there is a REL-commit which already has a
# Markdown-formatted git tag. Hence, the CHANGELOG is already adjusted,
# and it's decided what should be in the release.
# This action only ensures the release is done with the proper contents
# and that it's announced with a GitHub release.
name: Create git tag
# Disable for now and uses dummy `workflow_dispatch` trigger we usually do not use anyway.
# To activate this again, we have to fix https://github.com/py-pdf/pypdf/issues/2753
on:
    workflow_dispatch:
#   push:
#     branches:
#       - main

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

permissions: {}

env:
  HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}

jobs:
  build_and_publish:
    name: Publish a new version
    runs-on: ubuntu-latest
    if: "${{ startsWith(github.event.head_commit.message, 'REL: ') }}"
    permissions:
      contents: write  # Create the actual release.
    steps:
      - name: Checkout Repository
        uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10  # v6.0.3
        with:
          persist-credentials: false

      - name: Extract version from commit message
        id: extract_version
        run: |
          VERSION=$(echo "$HEAD_COMMIT_MESSAGE" | grep -oP '(?<=REL: )\d+\.\d+\.\d+')
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Extract tag message from commit message
        id: extract_message
        run: |
          VERSION="${STEPS_EXTRACT_VERSION_OUTPUTS_VERSION}"
          delimiter="$(openssl rand -hex 8)"
          MESSAGE=$(echo "$HEAD_COMMIT_MESSAGE" | sed "0,/REL: $VERSION/s///" )
          echo "message<<${delimiter}" >> $GITHUB_OUTPUT
          echo "$MESSAGE" >> $GITHUB_OUTPUT
          echo "${delimiter}" >> $GITHUB_OUTPUT
        env:
          STEPS_EXTRACT_VERSION_OUTPUTS_VERSION: ${{ steps.extract_version.outputs.version }}

      - name: Create Git Tag
        run: |
          VERSION="${STEPS_EXTRACT_VERSION_OUTPUTS_VERSION}"
          MESSAGE="${STEPS_EXTRACT_MESSAGE_OUTPUTS_MESSAGE}"
          git config user.name github-actions
          git config user.email github-actions@github.com
          git tag "$VERSION" -m "$MESSAGE"
          git push origin $VERSION
        env:
          STEPS_EXTRACT_VERSION_OUTPUTS_VERSION: ${{ steps.extract_version.outputs.version }}
          STEPS_EXTRACT_MESSAGE_OUTPUTS_MESSAGE: ${{ steps.extract_message.outputs.message }}
