name: Increment Build Number

on:
  pull_request:
    branches:
      - master
      - '*-develop'
    types:
      - closed
    paths:
      - 'src/**.php'

jobs:
  incremental-build-number:
    if: github.event.pull_request.merged == true
    name: Incremental Build Number
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
        with:
          ref: ${{ github.base_ref }}

      - name: Setup PHP
        uses: "shivammathur/setup-php@v2"
        with:
          php-version: '8.1'
          extensions: swoole, posix, json

      - name: Setup problem matchers for PHP
        run: echo "::add-matcher::${{ runner.tool_cache }}/php.json"

      - name: Get composer cache directory
        id: composer-cache
        run: echo "::set-output name=dir::$(composer config cache-files-dir)"

      - name: Cache dependencies
        uses: actions/cache@v2
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
          restore-keys: ${{ runner.os }}-composer-

      - name: Install Composer Dependencies
        run: "composer install --prefer-dist --no-progress --optimize-autoloader"

      - name: Generate API Docs
        id: generate-api-docs
        continue-on-error: true
        run: bin/gendoc

      - name: Commit API Docs
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: update api docs

      - name: Increment build number
        id: increment-build-number
        run: |
          sed -i -r 's/(.*)(\VERSION_ID\s=\s)([0-9]+)(.*)/echo "\1\2$((\3+1))\4"/ge' src/ZM/Framework.php
          BUILD_ID=$(cat src/ZM/Framework.php | grep "VERSION_ID = " | sed 's/[^0-9]//g')
          echo "::set-output name=build_id::$BUILD_ID"

      - name: Commit build number
        uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: increment build number (build ${{ steps.increment-build-number.outputs.build_id }})
