name: Auto-release via commit message

on:
  push:
    branches: [ master ]

permissions:
  contents: write

jobs:
  auto-release:
    runs-on:
      ubuntu-latest

    outputs:
      tag: ${{ steps.ver.outputs.version }}

    steps:
      - name: Checkout (full history for tags)
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Extract version of the commit message.
        id: ver
        run: |
          MSG="${{ github.event.head_commit.message }}"
          # The house exactly "V N.N.N" (with a space and 3 numbers)
          if echo "$MSG" | grep -Eq '^V [0-9]+\.[0-9]+\.[0-9]+$'; then
            VERSION=$(echo "$MSG" | sed -nE 's/^V ([0-9]+\.[0-9]+\.[0-9]+)$/\1/p')
            echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          else
            echo "No valid version in the message: '$MSG'."
          fi

      - name: Close if there is no version.
        if: steps.ver.outputs.version == ''
        run: |
          echo "Ignoring: commit is not a release."

      - name: Create annotated tag
        if: steps.ver.outputs.version != ''
        run: |
          VERSION="${{ steps.ver.outputs.version }}"
          git config user.name  "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          # usa sem prefixo (ex.: 1.2.3)
          git tag -a "$VERSION" -m "Release $VERSION"
          git push origin "$VERSION"

      - name: Create a Release on GitHub
        if: steps.ver.outputs.version != ''
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.ver.outputs.version }}
          name: ${{ steps.ver.outputs.version }}
          body: |
            Release ${{ steps.ver.outputs.version }} automatically generated by the commit:
            ${{ github.event.head_commit.id }}
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_PAT }}

  deploy-to-moodle:
    needs:
      auto-release

    if:
      needs.auto-release.outputs.tag != ''

    runs-on:
      ubuntu-latest

    env:
      PLUGIN: local_kopere_dashboard
      CURL: curl -s
      ENDPOINT: https://moodle.org/webservice/rest/server.php
      TOKEN: ${{ secrets.MOODLE_ORG_TOKEN }}
      FUNCTION: local_plugins_add_version
      TAGNAME: ${{ needs.auto-release.outputs.tag }}

    steps:
      - name: Call the service function
        id: add-version
        run: |
          if [[ ! -z "${{ github.event.inputs.tag }}" ]]; then
            TAGNAME="${{ github.event.inputs.tag }}"
          elif [[ $GITHUB_REF = refs/tags/* ]]; then
            TAGNAME="${GITHUB_REF##*/}"
          fi
          if [[ -z "${TAGNAME}" ]]; then
            echo "No tag name has been provided!"
            exit 1
          fi
          ZIPURL="https://api.github.com/repos/${{ github.repository }}/zipball/${TAGNAME}"
          RESPONSE=$(${CURL} ${ENDPOINT} --data-urlencode "wstoken=${TOKEN}" \
                                         --data-urlencode "wsfunction=${FUNCTION}" \
                                         --data-urlencode "moodlewsrestformat=json" \
                                         --data-urlencode "frankenstyle=${PLUGIN}" \
                                         --data-urlencode "zipurl=${ZIPURL}" \
                                         --data-urlencode "vcssystem=git" \
                                         --data-urlencode "vcsrepositoryurl=${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}" \
                                         --data-urlencode "vcstag=${TAGNAME}" \
                                         --data-urlencode "changelogurl=${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/commits/${TAGNAME}" \
                                         --data-urlencode "altdownloadurl=${ZIPURL}")
          echo "response=${RESPONSE}" >> $GITHUB_OUTPUT

      - name: Evaluate the response
        id: evaluate-response
        env:
          RESPONSE: ${{ steps.add-version.outputs.response }}
        run: |
          jq <<< ${RESPONSE}
          jq --exit-status ".id" <<< ${RESPONSE} > /dev/null
