name: Release WordPress Plugin

on:
  push:
    tags:
      - '*.*.*'
  workflow_dispatch:
    inputs:
      tag_override:
        description: 'Plugin tag for release (example: 1.2.3). Leave blank to draw from composer.json'
        required: false

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Determine tag and version
        id: determine_tag
        shell: bash
        run: |
          if [[ "${{ github.event_name }}" = "workflow_dispatch" && -n "${{ github.event.inputs.tag_override }}" ]]; then
            TAG="${{ github.event.inputs.tag_override }}"
          elif [[ "${{ github.event_name }}" != "workflow_dispatch" ]]; then
            TAG="${GITHUB_REF#refs/tags/}"
          else
            TAG="$(grep -E '"version"' composer.json | head -1 | sed -E 's/.*"version"[[:space:]]*:[[:space:]]*"([^\"]+)".*/\1/')"
          fi
          
          if [[ -z "$TAG" ]]; then
            echo "ERROR: could not determine TAG" >&2
            exit 1
          fi
          
          echo "TAG=${TAG}" >> $GITHUB_ENV
          echo "VERSION=${VERSION}" >> $GITHUB_ENV
      - name: Create git tag
        if: ${{ github.event_name == 'workflow_dispatch' }}
        shell: bash
        run: |
          if git rev-parse "${TAG}" >/dev/null 2>&1; then
            echo "Tag ${TAG} already exists, skipping."
          else
            git config user.name "github-actions[bot]"
            git config user.email "actions@github.com"
            git tag "${TAG}"
            git push origin "${TAG}"
            echo "Created and pushed tag ${TAG}"
          fi
      - name: Create release ZIP
        run: |
          PLUGIN_NAME=$(basename "$(pwd)")
          ZIP_NAME="${PLUGIN_NAME}-${VERSION}.zip"
          
          # Move to parent dir to include plugin folder in ZIP
          cd ..

          # Create ZIP, exclude VCS and config files
          zip -r "${ZIP_NAME}" "${PLUGIN_NAME}" \
            -x "${PLUGIN_NAME}/.git/*" \
            -x "${PLUGIN_NAME}/.github/*" \
            -x "${PLUGIN_NAME}/.gitignore" \
            -x "${PLUGIN_NAME}/composer.json" \
            -x "${PLUGIN_NAME}/composer.lock"

          # Move ZIP back to workspace
          mv "${ZIP_NAME}" "${GITHUB_WORKSPACE}"
          cd "${GITHUB_WORKSPACE}"
          
          # Export ZIP_NAME
          echo "ZIP_NAME=${ZIP_NAME}" >> $GITHUB_ENV
      - name: Create GitHub Release
        id: create_release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ env.TAG }}
          name: Release ${{ env.TAG }}
          files: ${{ env.ZIP_NAME }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}