name: Create New Release

on:
  workflow_dispatch:
    inputs:
      new_tag:
        description: 'Tag name for the new release'
        required: true

jobs:
  create_release:
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get latest release tag from GitHub
        id: latest_release
        uses: actions/github-script@v6
        with:
          script: |
            try {
              const latestRelease = await github.rest.repos.getLatestRelease({
                owner: context.repo.owner,
                repo: context.repo.repo
              });
              core.info(`Latest release tag: ${latestRelease.data.tag_name}`);
              core.setOutput('last_release', latestRelease.data.tag_name);
            } catch (error) {
              core.info("No previous release found.");
              // If no release exists, output an empty string.
              core.setOutput('last_release', '');
            }

      - name: Set new release tag from input
        id: new_tag
        run: |
          echo "NEW_TAG=${{ github.event.inputs.new_tag }}" >> $GITHUB_OUTPUT

      - name: Generate commit log for new release
        id: commits
        run: |
          LAST_RELEASE="${{ steps.latest_release.outputs.last_release }}"
          NEW_TAG="${{ steps.new_tag.outputs.NEW_TAG }}"

          if [ -z "$NEW_TAG" ]; then
            echo "No new tag provided. Exiting."
            exit 1
          fi

          if [ -z "${LAST_RELEASE}" ]; then
            echo "No previous release found, using the repository’s initial commit as the starting point."
            FIRST_COMMIT=$(git rev-list --max-parents=0 HEAD)
            RANGE="${FIRST_COMMIT}..${NEW_TAG}"
          else
            RANGE="${LAST_RELEASE}..${NEW_TAG}"
          fi

          echo "Comparing commits between: ${RANGE}"
          LOG=$(git log "${RANGE}" --no-merges --pretty=format:"- %h %s by %an")

          echo "LOG<<EOF" >> "$GITHUB_ENV"
          echo "$LOG" >> "$GITHUB_ENV"
          echo "EOF" >> "$GITHUB_ENV"

      # Create or update the GitHub release for the new tag.
      - name: Create / Update GitHub Release for new tag
        uses: softprops/action-gh-release@master
        with:
          tag_name: ${{ steps.new_tag.outputs.NEW_TAG }}
          name: "${{ steps.new_tag.outputs.NEW_TAG }}"
          body: ${{ env.LOG }}
          append_body: false
          generate_release_notes: true
          make_latest: true
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
