---
# This action is centrally managed in https://github.com/<organization>/.github/
# Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in
# the above-mentioned repo.

# This action receives a dispatch event and passes it through to another repo. This is a workaround to avoid issues
# where fork PRs do not have access to secrets.

name: Dispatcher

on:
  workflow_dispatch:
    inputs:
      dispatch_repository:
        description: 'Repository to dispatch to'
        required: true
      dispatch_workflow:
        description: 'Workflow to dispatch to'
        required: true
      dispatch_ref:
        description: 'Ref/branch to dispatch to'
        required: true
      dispatch_inputs:
        description: 'Inputs to send'
        required: true

jobs:
  dispatcher:
    name: Repository Dispatch
    runs-on: ubuntu-latest
    steps:
      - name: Unescape JSON control characters
        id: inputs
        run: |
          # get the inputs
          dispatch_inputs=${{ github.event.inputs.dispatch_inputs }}
          echo "$dispatch_inputs"

          # temporarily replace newlines with a placeholder
          dispatch_inputs=$(echo ${dispatch_inputs} | sed 's/\\\\n/_!new_line!_/g')

          # remove newline characters
          dispatch_inputs=$(echo ${dispatch_inputs} | sed 's/\\n//g')

          # replace placeholder with newline
          dispatch_inputs=$(echo ${dispatch_inputs} | sed 's/_!new_line!_/\\n/g')

          # replace escaped quotes with unescaped quotes
          dispatch_inputs=$(echo ${dispatch_inputs} | sed 's/\\"//g')

          # debug echo
          echo "$dispatch_inputs"

          # parse as JSON
          dispatch_inputs=$(echo "$dispatch_inputs" | jq -c .)

          # debug echo
          echo "$dispatch_inputs"

          echo "dispatch_inputs=$dispatch_inputs" >> $GITHUB_OUTPUT

      - name: Workflow Dispatch
        uses: benc-uk/workflow-dispatch@v1.2.2
        with:
          repo: ${{ github.event.inputs.dispatch_repository }}
          ref: ${{ github.event.inputs.dispatch_ref || 'master' }}  # default to master if not specified
          workflow: ${{ github.event.inputs.dispatch_workflow }}
          inputs: ${{ steps.inputs.outputs.dispatch_inputs }}
          token: ${{ secrets.GH_BOT_TOKEN || github.token }}  # fallback to default token if not specified
