name: CI-trigger

on:
  workflow_dispatch:
  workflow_call:

jobs:
  trigger:
    runs-on: ubuntu-22.04

    steps:
    - name: Trigger workflow_run[in_progress]
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        set +e
        #set -x

        RUNNAME1="${{ github.event.after || github.sha }}"
        RUNNAME2="${{ github.event.pull_request.head.sha || github.sha }}"
        RUNNAME3="${{ github.sha }}"
        echo "Get run id: '${RUNNAME1}|${RUNNAME2}|${RUNNAME3}' ..."
        sleep 5
        RUNID=$(gh -R ${{ github.repository }} run list -w CI-builds -s in_progress | grep -P "${RUNNAME1}|${RUNNAME2}|${RUNNAME3}" | grep -Po '(?<=workflow_run)\s+\d+')
        while [[ -z ${RUNID} ]]; do
          sleep 20
          gh -R ${{ github.repository }} run list -w CI-builds -s in_progress | grep -P "${RUNNAME1}|${RUNNAME2}|${RUNNAME3}"
          RUNID=$(gh -R ${{ github.repository }} run list -w CI-builds -s in_progress | grep -P "${RUNNAME1}|${RUNNAME2}|${RUNNAME3}" | grep -Po '(?<=workflow_run)\s+\d+')
        done
        echo "Got run id: '${RUNNAME1}|${RUNNAME2}|${RUNNAME3}' : '${RUNID}'"
        
        echo "Trigger workflow_run[in_progress]: '${RUNNAME1}|${RUNNAME2}|${RUNNAME3}'"
        sleep 5
        # this blocks until the run is finished
        gh -R ${{ github.repository }} run watch -i 30 ${RUNID} >/dev/null
        sleep 5

    - name: Trigger workflow_run[completed]
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        echo "Cleanup skipped ..."
        gh -R ${{ github.repository }} run list -s skipped -L 100 --json databaseId  -q '.[].databaseId' | xargs -r -n1 gh -R ${{ github.repository }} run delete
        echo "Triggered workflow_run[completed]: '${{ github.ref_name }} ${{ github.workflow }} ${{ github.sha }}'"
        
