name: Composer update

on:
  workflow_dispatch:
  schedule:
  - cron: "0 2 * * 5"

permissions:
  actions: read
  checks: none
  contents: write
  deployments: none
  issues: read
  packages: none
  pull-requests: write
  repository-projects: none
  security-events: none
  statuses: none

jobs:
  build:

    runs-on: ubuntu-24.04

    steps:
    - uses: actions/checkout@v6
      with:
        ref: '5.x-dev'
        lfs: false
        persist-credentials: false
    - name: Install composer dependencies
      run: composer install
    - name: Prepare branches
      run: |
          cat <<- EOF > $HOME/.netrc
            machine github.com
            login $GITHUB_ACTOR
            password $GITHUB_TOKEN
            machine api.github.com
            login $GITHUB_ACTOR
            password $GITHUB_TOKEN
          EOF
          chmod 600 $HOME/.netrc

          git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com"
          git config --global user.name "$GITHUB_ACTOR"
          git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY

          git remote add upstream https://github.com/${GITHUB_REPOSITORY}.git

          git push origin --delete composer-update || true
          git branch -D composer-update || true
          git fetch upstream 5.x-dev
          git checkout -f upstream/5.x-dev
          git branch composer-update
          git checkout -f composer-update
    - name: Update composer dependencies
      id: update
      run: |
          composer update --no-ansi 2>&1 | tee COMPOSER_LOG
          sed -i -e '1i```\' COMPOSER_LOG
          sed -i -e '1icomposer update log:\' COMPOSER_LOG
          echo '```' &>> COMPOSER_LOG

          changes=( $(git diff composer.lock) )
          git add "composer.lock"

          # abort here if no change available
          if [[ ${#changes[@]} -eq 0 ]]
          then
              exit 0
          fi

          echo "message=$(cat COMPOSER_LOG | jq -aRs)" >> $GITHUB_OUTPUT
      shell: bash
    - name: Push changes
      run: |
          git commit -m "Update composer dependencies"
          git push --set-upstream origin composer-update
      shell: bash
      if: steps.update.outputs.message
    - name: Create PR
      run: |
          message=
          curl \
                 --request POST \
                 --header 'authorization: Bearer ${{ secrets.CUSTOM_ACCESS_TOKEN }}' \
                 --header 'content-type: application/json' \
                 --data '{
                  "title":"[automatic composer updates]",
                  "body":${{ steps.update.outputs.message }},
                  "head":"composer-update",
                  "base":"5.x-dev"
                  }' \
                 --url https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls
      shell: bash
      if: steps.update.outputs.message
