name: GitHub Release
on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version number to release'
        required: true

env:
  GHP_BASE_URL: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}

jobs:
  release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          show-progress: false

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: 3.12

      - name: Install PyYaml
        run: pip install pyyaml ansible-core

      - name: Validate version is published to Galaxy
        run: ansible-galaxy collection download -vvv -p /tmp 'community.hashi_vault:==${{ github.event.inputs.version }}'

      - name: Build release description
        shell: python
        run: |
          import os
          import yaml

          ver = '${{ github.event.inputs.version }}'
          ver_anchor = str.replace(ver, '.', '-')

          with open('changelogs/changelog.yaml', 'r') as s:
              ri = yaml.safe_load(s)

          summary = ri['releases'][ver]['changes']['release_summary']
          reldate = ri['releases'][ver]['release_date']

          description = '''## Summary
          Released: %s

          %s

          ---

          View the [complete changelog](https://github.com/ansible-collections/community.hashi_vault/blob/main/CHANGELOG.rst#v%s) to see all changes.

          View the [full documentation for release ${{ github.event.inputs.version }}](${{ env.GHP_BASE_URL }}/tag/${{ github.event.inputs.version }}).
          ''' % (reldate, summary, ver_anchor)

          with open(os.environ['GITHUB_ENV'], 'a') as e:
              e.write("RELEASE_DESCRIPTION<<EOF\n%s\nEOF" % description)

      - name: Create Release
        id: create_release
        # TODO: this action is no longer maintained, replace
        # likely candidate: https://github.com/softprops/action-gh-release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ github.event.inputs.version }}
          release_name: ${{ github.event.inputs.version }}
          body: ${{ env.RELEASE_DESCRIPTION }}
