on:
  workflow_call:
    inputs:
      distrib:
        required: true
        type: string
      arch:
        required: true
        type: string
      test_img_version:
        required: true
        type: string
      database_type:
        required: true
        type: string
      tests_params:
        required: true
        type: string
      is_nightly:
        required: false
        type: string
      features_pattern:
        required: false
        type: string
        default: .robot
      store_docker_image_in_cache:
        required: false
        type: boolean
        default: true
    secrets:
      registry_username:
        required: true
      registry_password:
        required: true
      collect_s3_access_key:
        required: true
      collect_s3_secret_key:
        required: true
      xray_client_id:
        required: true
      xray_client_secret:
        required: true
      jira_base_url:
        required: true
      jira_user_email:
        required: true
      jira_api_token:
        required: true

jobs:
  test-image-to-cache:
    if: ${{ inputs.store_docker_image_in_cache == true }}
    runs-on: ${{ inputs.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }}
    env:
      IMAGE_NAME: centreon-collect-${{ inputs.database_type }}-${{ inputs.distrib }}${{ inputs.arch == 'arm64' && '-arm64' || '' }}-test
    steps:
      - name: Checkout sources
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: Login to Registry
        uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
        with:
          registry: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}
          username: ${{ secrets.registry_username }}
          password: ${{ secrets.registry_password }}

      - name: Login to Proxy Registry
        uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
        with:
          registry: ${{ vars.DOCKER_PROXY_REGISTRY_URL }}
          username: ${{ secrets.registry_username }}
          password: ${{ secrets.registry_password }}

      - name: load and save image to disk
        run: |
          docker pull ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}/${{ env.IMAGE_NAME }}:${{ inputs.test_img_version }}
          docker save -o ./${{ env.IMAGE_NAME }} ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}/${{ env.IMAGE_NAME }}:${{ inputs.test_img_version }}
        shell: bash

      - name: image to cache
        uses: actions/cache/save@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
        with:
          path: ./${{ env.IMAGE_NAME }}
          key: ${{ env.IMAGE_NAME }}:${{ inputs.test_img_version }}

  robot-test-list:
    runs-on: ubuntu-24.04
    outputs:
      test_group_name: robot_test-${{ inputs.distrib }}-${{ inputs.database_type }}-${{ inputs.arch }}${{ contains(inputs.tests_params, 'grpc') && '-grpc' || '' }}
      features: ${{ steps.list-features.outputs.features }}

    steps:
      - name: Checkout sources
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: List features
        id: list-features
        run: |
          cd tests

          #when tests are executed by github cron, inputs are empty as centreon-collect.yml input default value is not used
          FEATURES_PATTERN="${{ inputs.features_pattern }}"
          if [ "0" = "0${FEATURES_PATTERN}" ]; then
            FEATURES_PATTERN='^((?!cma).)*$'
          fi

          features=$(grep -Rl '*** Test Cases ***' . | grep -P '.robot$' | grep -P "${FEATURES_PATTERN}" | sed -e "s#^./##" | sort | jq -R -s -c 'split("\n")[:-1]')
          if [[ "${{ inputs.database_type }}" == "mysql" ]]; then
            for feature in $(echo "${features}" | jq -r '.[]'); do
              if [[ ! -f "$feature.mysql" ]]; then
                features=$(echo "${features}" | jq -c "del(.[index(\"$feature\")])")
              fi
            done
          fi

          echo $features
          echo "features=${features}" >> $GITHUB_OUTPUT

  robot-test:
    if: |
      ! cancelled() &&
      ! contains(needs.*.result, 'cancelled')
    needs: [robot-test-list, test-image-to-cache]
    runs-on: ${{ inputs.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }}

    strategy:
      fail-fast: false
      matrix:
        feature: ${{ fromJson(needs.robot-test-list.outputs.features) }}

    name: ${{ matrix.feature }}

    env:
      IMAGE_NAME: centreon-collect-${{ inputs.database_type }}-${{ inputs.distrib }}${{ inputs.arch == 'arm64' && '-arm64' || '' }}-test

    steps:
      - name: Checkout sources
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: Parse distrib name
        id: parse-distrib
        uses: ./.github/actions/parse-distrib
        with:
          distrib: ${{ inputs.distrib }}

      - name: Restore image
        id: restore-image
        uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
        with:
          path: ./${{ env.IMAGE_NAME }}
          key: ${{ env.IMAGE_NAME }}:${{ inputs.test_img_version }}
          fail-on-cache-miss: ${{ inputs.store_docker_image_in_cache == true }}

      - name: Restore packages
        uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
        with:
          path: ./*.${{ steps.parse-distrib.outputs.package_extension }}
          key: ${{ github.run_id }}-${{ github.sha }}-${{ steps.parse-distrib.outputs.package_extension }}-centreon-collect-${{ steps.parse-distrib.outputs.repo_distrib_name }}-${{ inputs.arch }}-${{ github.head_ref || github.ref_name }}
          fail-on-cache-miss: true

      - name: load image
        if: steps.restore-image.outputs.cache-hit == 'true'
        run: |
          docker load --input ./${{ env.IMAGE_NAME }}

      - name: Login to Registry
        if: steps.restore-image.outputs.cache-hit != 'true'
        uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
        with:
          registry: ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}
          username: ${{ secrets.registry_username }}
          password: ${{ secrets.registry_password }}

      #  pam sshd authentication doesn't work with privileged containers
      - name: ${{ matrix.feature == 'connector_ssh/connector_ssh.robot' && format('Test {0} (without privileges)', matrix.feature) || format('Test {0}', matrix.feature) }}
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.collect_s3_access_key }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.collect_s3_secret_key }}
        run: |
          privilege_status=""
          if [[ ${{ matrix.feature }} != 'connector_ssh/connector_ssh.robot' ]]; then
            privilege_status="--privileged"
          fi
          docker run --rm $privilege_status --ulimit core=-1 --ulimit nofile=524288:1048576 --security-opt seccomp=unconfined \
            -v $(pwd):/test_collect  \
            --env AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \
            --env AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \
            --env AWS_BUCKET=centreon-collect-robot-report \
            --workdir /test_collect \
            ${{ vars.DOCKER_INTERNAL_REGISTRY_URL }}/${{ env.IMAGE_NAME }}:${{ inputs.test_img_version }} \
            ./.github/scripts/collect-test-robot.sh \
            ${{ matrix.feature }} ${{ inputs.database_type }} '${{ inputs.tests_params }}'

      # - name: Generate Xray Token
      #   id: generate-xray-token
      #   run: |
      #     token_response=$(curl -H "Content-Type: application/json" -X POST --data "{\"client_id\": \"${{ secrets.XRAY_CLIENT_ID }}\", \"client_secret\": \"${{ secrets.XRAY_CLIENT_SECRET }}\"}" "https://xray.cloud.getxray.app/api/v1/authenticate")
      #     xray_token=$(echo "$token_response" | sed -n 's/.*"\(.*\)".*/\1/p')
      #     echo "xray_token=$xray_token" >> $GITHUB_OUTPUT
      #   shell: bash

      # - name: Send report to xrays
      #   run: |
      #     curl -H "Content-Type: multipart/form-data" -X POST -F info=@tests/issueFields.json -F results=@tests/output.xml -F testInfo=@tests/testIssueFields.json -H "Authorization: Bearer ${{ steps.generate-xray-token.outputs.xray_token }}" https://xray.cloud.getxray.app/api/v2/import/execution/robot/multipart

      - name: Move reports
        if: ${{ failure() }}
        run: |
          mkdir -p reports
          FILE_PREFIX=`echo "${{ matrix.feature }}" | sed -e "s#/#__#g"`-${{ needs.robot-test-list.outputs.test_group_name }}
          if [ -d tests/failed ] ; then
            cp -rp tests/failed reports/$FILE_PREFIX-failed
          fi
          if [ -f tests/log.html ] ; then
            cp tests/log.html reports/$FILE_PREFIX-log.html
          fi
          if [ -f tests/output.xml ] ; then
            cp tests/output.xml reports/$FILE_PREFIX-output.xml
          fi
          if [ -f tests/report.html ] ; then
            cp tests/report.html reports/$FILE_PREFIX-report.html
          fi

      - name: Replace / with - in the feature path
        id: feature-path
        if: ${{ ! cancelled() }}
        run: |
          feature_name="${{ matrix.feature }}"
          feature_name_with_dash="${feature_name//\//-}"
          echo "Modified Feature Name: $feature_name_with_dash"
          echo "feature_name_with_dash=$feature_name_with_dash" >> $GITHUB_OUTPUT

      - name: Upload Test Results
        if: ${{ failure() }}
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
        with:
          name: reports-${{ needs.robot-test-list.outputs.test_group_name }}-${{ steps.feature-path.outputs.feature_name_with_dash }}
          path: reports
          retention-days: 1

  robot-test-report:
    needs: [robot-test-list, robot-test]
    if: |
      failure() &&
      ! contains(needs.*.result, 'cancelled')
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: Download Artifacts
        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
        with:
          pattern: reports-${{ needs.robot-test-list.outputs.test_group_name }}-*
          path: reports
          merge-multiple: true

      - name: Upload the regrouped artifact
        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
        with:
          name: reports-${{ needs.robot-test-list.outputs.test_group_name }}
          path: reports/
          retention-days: 1

      - name: Delete separated artifacts
        run: |
          artifact_pattern="reports-${{ needs.robot-test-list.outputs.test_group_name }}-"
          TOKEN=${{ secrets.GITHUB_TOKEN }}
          artifact_exist=true
          while [ "$artifact_exist" = true ] ;do
            artifact_exist=false
            artifacts_response=$(curl -L \
                          -H "Accept: application/vnd.github+json" \
                          -H "Authorization: Bearer $TOKEN" \
                          -H "X-GitHub-Api-Version: 2022-11-28" \
                          "https://api.github.com/repos/${{ github.repository }}/actions/artifacts?per_page=100")
            artifacts=$(echo $artifacts_response | jq -c '.artifacts[]')
            echo "Those are the artifacts : $artifacts"
            while read row; do
              artifact_name=$(echo "$row" | jq -r '.name')
              if [[ "$artifact_name" =~ ^.*"$artifact_pattern".* ]]; then
                artifact_exist=true
                echo "Deleting : $artifact_name"
                artifact_id=$(echo "$row" | jq -r '.id')
                curl -L \
                  -X DELETE \
                  -H "Accept: application/vnd.github+json" \
                  -H "Authorization: Bearer $TOKEN" \
                  -H "X-GitHub-Api-Version: 2022-11-28" \
                  "https://api.github.com/repos/${{ github.repository }}/actions/artifacts/${artifact_id}"
              fi
            done <<< "$artifacts"
          done
          echo "End of Deleting"
        shell: bash

      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
        with:
          python-version: "3.10"

      - run: |
          pip3 install -U robotframework robotframework-databaselibrary pymysql python-dateutil
          cd reports
          rebot -o output.xml ./*-output.xml || true
        shell: bash

      - name: Send report to commit
        uses: joonvena/robotframework-reporter-action@229b6d4248b20be6e54f4fc32c7414130d1bf200 # v2.5
        with:
          gh_access_token: ${{ secrets.GITHUB_TOKEN }}
          report_path: reports
          show_passed_tests: false
