name: Dispatcher

on:
  push:
    branches:
      - '**'

permissions:
  contents: write

jobs:
  dispatch:
    runs-on: self-hosted
    outputs:
      engine: ${{ steps.check.outputs.engine }}
      server: ${{ steps.check.outputs.server }}
      ui: ${{ steps.check.outputs.ui }}
    steps:
      - name: checkout repository 
        uses: actions/checkout@v4

      - name: Determine which tests to run
        id: check
        run: |
          BRANCH="${{ github.ref_name }}"
          echo "Branch: $BRANCH"

          ENGINE=false
          SERVER=false
          UI=false

          if [[ "$BRANCH" == *"Engine"* ]] ; then
            ENGINE=true
          fi
          if [[ "$BRANCH" == *"Server"* ]] ; then
            SERVER=true
          fi
          if [[ "$BRANCH" == *"UI"* ]] ; then
            UI=true
          fi

          # Run all on master
          if [[ "$BRANCH" == "master" ]]; then
            ENGINE=true
            SERVER=true
            UI=true
          fi

          echo "engine=$ENGINE" >> $GITHUB_OUTPUT
          echo "server=$SERVER" >> $GITHUB_OUTPUT
          echo "ui=$UI" >> $GITHUB_OUTPUT

  engine:
    needs: dispatch
    if: needs.dispatch.outputs.engine == 'true'
    uses: ./.github/workflows/engine_test.yml
    secrets: inherit

  server:
    needs: dispatch
    if: needs.dispatch.outputs.server == 'true'
    uses: ./.github/workflows/server_test.yml
    secrets: inherit

  ui:
    needs: dispatch
    if: needs.dispatch.outputs.ui == 'true'
    uses: ./.github/workflows/ui_test.yml
    secrets: inherit
    

  test-data-upload:
    needs: [engine, server, ui]
    if: always()
    uses: ./.github/workflows/upload_data.yml
    secrets: inherit


  release:
    needs: test-data-upload
    if: github.ref == 'refs/heads/master'
    uses: ./.github/workflows/release.yml
    secrets: inherit

  cleanup:
    runs-on: self-hosted
    needs: [engine, server, ui, test-data-upload, release]
    if: always()
    steps:
      - name: Final cleanup
        run: |
          echo "Final cleanup on self-hosted runner..."
          cd "$GITHUB_WORKSPACE"
          git clean -fdx
          git reset --hard



