# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

# Support push and pull_request events
name: Get Test Matrix
permissions: read-all
on:
  workflow_call:
    inputs:
      diff_excluded_files:
        required: false
        type: string
        default: '.github|README.md|*.txt'
      test_mode:
        required: false
        type: string
        default: 'docker_compose'
    outputs:
      run_matrix:
        description: "The matrix string"
        value: ${{ jobs.job1.outputs.run_matrix }}

jobs:
  job1:
    name: Get-test-matrix
    runs-on: ubuntu-latest
    outputs:
      run_matrix: ${{ steps.get-test-matrix.outputs.run_matrix }}
    steps:
      - name: Get checkout ref
        run: |
          if [ "${{ github.event_name }}" == "pull_request" ] || [ "${{ github.event_name }}" == "pull_request_target" ]; then
            echo "CHECKOUT_REF=refs/pull/${{ github.event.number }}/merge" >> $GITHUB_ENV
          else
            echo "CHECKOUT_REF=${{ github.ref }}" >> $GITHUB_ENV
          fi
          echo "checkout ref ${{ env.CHECKOUT_REF }}"

      - name: Checkout out Repo
        uses: actions/checkout@v4
        with:
          ref: ${{ env.CHECKOUT_REF }}
          fetch-depth: 0

      - name: Get test matrix
        id: get-test-matrix
        run: |
          if [ "${{ github.event_name }}" == "pull_request" ] || [ "${{ github.event_name }}" == "pull_request_target" ]; then
            LATEST_COMMIT_SHA=$(curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            "https://api.github.com/repos/opea-project/GenAIExamples/commits?sha=${{ github.event.pull_request.base.ref }}" | jq -r '.[0].sha')
            echo "Latest commit SHA is $LATEST_COMMIT_SHA"
            base_commit=$LATEST_COMMIT_SHA
          else
            base_commit=$(git rev-parse HEAD~1) # push event
          fi
          merged_commit=$(git log -1 --format='%H')
          changed_files="$(git diff --name-only ${base_commit} ${merged_commit} | \
          grep -vE '${{ inputs.diff_excluded_files }}')" || true
          echo "changed_files=$changed_files"
          export changed_files=$changed_files
          export test_mode=${{ inputs.test_mode }}
          export WORKSPACE=${{ github.workspace }}
          bash .github/workflows/scripts/get_test_matrix.sh
