# Matomo Release Action
#
# Required GitHub secrets:
#
# RELEASE_PASSWORD  |  password that needs to be provided to start the action
# GPG_CERTIFICATE  |  ASCII armored or Base64 encoded GPG certificate that is used to create the signatures for the archives
# GPG_CERTIFICATE_PASS  |  Passphrase of the GPG key

name: Build release

permissions:
  actions: none
  checks: none
  contents: write  # required to create tag and release
  deployments: none
  issues: none
  packages: none
  pull-requests: none
  repository-projects: none
  security-events: none
  statuses: none

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Or specify a tag to build from'
        required: false
        default: ''
      password:
        description: 'Release password'
        required: true
  workflow_call:
    inputs:
      is_preview:
        type: boolean
        required: false
        default: false
      ref:
        type: string
        required: false
        default: ''
    secrets:
      RELEASE_PASSWORD:
        description: 'Release password'
        required: true
      GPG_CERTIFICATE:
        description: 'GPG Certificate'
        required: true
      GPG_CERTIFICATE_PASS:
        description: 'GPG Certificate Pass'
        required: true
env:
  RELEASE_PASSWORD: ${{ secrets.RELEASE_PASSWORD }}

jobs:
  release:
    runs-on: ubuntu-24.04
    steps:
      - name: "Check release password"
        if: ${{ inputs.is_preview != true && github.event.inputs.password != env.RELEASE_PASSWORD }}
        uses: actions/github-script@v8
        with:
          script: |
              core.setFailed('Release password didn\'t match.')
      - name: "Check if user is allowed"
        if: ${{ inputs.is_preview != true && github.actor != 'mattab' && github.actor != 'tsteur' && github.actor != 'sgiehl' && github.actor != 'mneudert' && github.actor != 'caddoo' && github.actor != 'nathangavin' && github.actor != 'chippison' && github.actor != 'tzi'}}
        uses: actions/github-script@v8
        with:
          script: |
            core.setFailed('User is not allowed to release.')
      - uses: actions/checkout@v6
        with:
          lfs: false
          ref: ${{ inputs.ref || github.ref }}
      - name: Import GPG key
        id: import_gpg
        run: |
          echo "${{ secrets.GPG_CERTIFICATE }}" > $HOME/private.asc
          gpg --import --batch --yes $HOME/private.asc
          echo "default-cache-ttl 7200
          max-cache-ttl 31536000
          allow-preset-passphrase" > $HOME/.gnupg/gpg-agent.conf
          keygrip=$(gpg --import --import-options show-only --with-keygrip $HOME/private.asc | grep "Keygrip" | grep -oP "([A-F0-9]+)" | head -1)
          hexPassphrase=$( echo -n '${{ secrets.GPG_CERTIFICATE_PASS }}' | od -A n -t x1 -w100 | sed 's/ *//g' )
          gpg-connect-agent "RELOADAGENT" /bye
          gpg-connect-agent "PRESET_PASSPHRASE ${keygrip} -1 ${hexPassphrase}" /bye
          gpg-connect-agent "KEYINFO ${keygrip}" /bye
      - name: Check preconditions, create tag, build and publish release
        id: tag
        run: |
          if [[ -n "${{ github.event.inputs.version }}" ]]
          then
            version="${{ github.event.inputs.version }}"
            echo "Version to re-build: '$version'"

            git fetch --tags -q 2>/dev/null
            tag_exists=$( git tag --list "$version" )

            if [[ -z "$tag_exists" ]]
            then
              echo "A tag for $version does not exist."
              exit 1
            fi

            echo "update=true" >> $GITHUB_OUTPUT
          else
            version=$( cat core/Version.php | grep -oP "VERSION = '\K([^\']+)" )
            echo "Version to build: '$version'"

            git fetch --tags -q 2>/dev/null
            tag_exists=$( git tag --list "$version" )

            if [[ -n "$tag_exists" ]]
            then
              echo "A tag for $tag_exists already exists."
              exit 1
            fi

            if ! [[ ${GITHUB_REF#refs/heads/} =~ ^[4-9]\.x-(dev|preview)$ || ${GITHUB_REF#refs/heads/} == "next_release" ]]
            then
              echo "A tag can only be created from branches '5.x-dev', '5.x-preview' or 'next_release'. Please create the tag manually if a release needs to be built from another branch."
              exit 1
            fi

            if [[ ${GITHUB_REF#refs/heads/} =~ ^[4-9]\.x-dev$ && $version =~ ^[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?$ ]]
            then
              echo "Only beta release tags can be created from ${GITHUB_REF#refs/heads/} branch."
              exit 1
            fi

            if [[ ${GITHUB_REF#refs/heads/} =~ ^[4-9]\.x-preview$ && $version =~ [0-9]{14}$ ]]
            then
              echo "Only preview release tags can be created from ${GITHUB_REF#refs/heads/} branch."
              exit 1
            fi

            echo "Creating a tag for $version"

            git tag $version
            git push origin tags/$version

            echo "update=false" >> $GITHUB_OUTPUT
          fi

          if [[ "$version" =~ "-" ]]
          then
            echo "prerelease=true" >> $GITHUB_OUTPUT
            body="## Matomo ${version} (Pre-release)

            We recommend to read [this FAQ](https://matomo.org/faq/how-to-update/faq_159/) before using a pre-release in a production environment.

            Please use the attached archives for installing or updating Matomo.
            The source code download is only meant for developers and will require extra work to install it.
             - Latest stable production release can be found at https://matomo.org/download/ ([learn more](https://matomo.org/docs/installation/)) (recommended)
             - Beta and Release Candidate releases can be found at https://builds.matomo.org/ ([learn more](https://matomo.org/faq/how-to-update/faq_159/))"
          else
            echo "prerelease=false" >> $GITHUB_OUTPUT
            body="## [Matomo ${version} Changelog](https://matomo.org/changelog/matomo-${version//./-}/)

            Please use the attached archives for installing or updating Matomo.
            The source code download is only meant for developers and will require extra work to install it.
             - Latest stable production release can be found at https://matomo.org/download/ ([learn more](https://matomo.org/docs/installation/)) (recommended)
             - Beta and Release Candidate releases can be found at https://builds.matomo.org/ ([learn more](https://matomo.org/faq/how-to-update/faq_159/))"
          fi

          echo "version=$version" >> $GITHUB_OUTPUT
          echo 'body<<EOF' >> $GITHUB_OUTPUT
          echo "$body" >> $GITHUB_OUTPUT
          echo 'EOF' >> $GITHUB_OUTPUT

          cd $GITHUB_WORKSPACE
          chmod 755 ./.github/scripts/*.sh
          ./.github/scripts/build-package.sh $version
        shell: bash
      - uses: ncipollo/release-action@b7eabc95ff50cbeeedec83973935c8f306dfcd0b
        with:
          artifacts: "archives/matomo-${{ steps.tag.outputs.version }}.*,archives/piwik-${{ steps.tag.outputs.version }}.*"
          allowUpdates: ${{ steps.tag.outputs.update }}
          tag: ${{ steps.tag.outputs.version }}
          body: "${{ steps.tag.outputs.body }}"
          prerelease: ${{ steps.tag.outputs.prerelease }}
          token: ${{ secrets.GITHUB_TOKEN }}
