name: Commit Changes

on:
  workflow_call:
    inputs:
      artifact-name:
        description: Name of artifact containing changes.patch
        required: true
        type: string
      commit-message:
        description: Commit message
        required: true
        type: string
      ref:
        description: Git ref to checkout
        required: false
        type: string
        default: ''
      push-branch:
        description: Branch to force push to; if unset, pushes to the checked-out branch without force
        required: false
        type: string
        default: ''
    secrets:
      SELENIUM_CI_TOKEN:
        required: false

jobs:
  commit:
    name: Commit Changes
    runs-on: ubuntu-latest
    permissions:
      contents: write
      actions: read
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          ref: ${{ inputs.ref || github.ref }}
          token: ${{ secrets.SELENIUM_CI_TOKEN || github.token }}
      - name: Download patch
        uses: actions/download-artifact@v8
        with:
          name: ${{ inputs.artifact-name }}
        continue-on-error: true
      - name: Apply and commit
        run: |
          git config --local user.email "selenium-ci@users.noreply.github.com"
          git config --local user.name "Selenium CI Bot"
          if [ -s changes.patch ]; then
            git apply --index changes.patch
            git commit -m "$COMMIT_MESSAGE"
            if [ -n "$PUSH_BRANCH" ]; then
              git push --force origin HEAD:"$PUSH_BRANCH"
            else
              git push
            fi
          else
            echo "::notice::No changes.patch found or patch is empty; skipping commit and push."
          fi
        env:
          COMMIT_MESSAGE: ${{ inputs.commit-message }}
          PUSH_BRANCH: ${{ inputs.push-branch }}
