# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Test
name: Build latest images on push event

on:
  push:
    branches: ["main"]
    paths:
      - comps/**
      - "!**.md"
      - "!**.txt"
      - "**requirements.txt"
      - .github/workflows/push-image-build.yml

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}-on-push
  cancel-in-progress: true

jobs:
  get-build-matrix:
    runs-on: ubuntu-latest
    outputs:
      services: ${{ steps.get-services.outputs.services }}
    steps:
      - name: Checkout out Repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get Test Services
        id: get-services
        run: |
          base_commit=$(git rev-parse HEAD~1)
          merged_commit=$(git log -1 --format='%H')
          changed_files="$(git diff --name-only ${base_commit} ${merged_commit} | grep 'comps/' | grep -vE '\.md|\.txt|comps/cores')" || true
          services=$(printf '%s\n' "${changed_files[@]}" | cut -d'/' -f2 | grep -vE '\.py' | sort -u | jq -R '.' | jq -sc '.') || true
          echo "services=$services"
          echo "services=$services" >> $GITHUB_OUTPUT

  image-build:
    needs: get-build-matrix
    strategy:
      matrix:
        service: ${{ fromJSON(needs.get-build-matrix.outputs.services) }}
        node: [docker-build-xeon, docker-build-gaudi]
    runs-on: ${{ matrix.node }}
    continue-on-error: true
    steps:
      - name: Clean up Working Directory
        run: |
          sudo rm -rf ${{github.workspace}}/*

      - name: Checkout out Repo
        uses: actions/checkout@v4

      - name: Check Docker Compose File Exists
        env:
          service: ${{ matrix.service }}
        run: |
          docker_compose_path="${{ github.workspace }}/.github/workflows/docker/compose/${service}-compose.yaml"
          if [ -e $docker_compose_path ]; then
            echo "file_exists=true" >> $GITHUB_ENV
            echo "docker_compose_path=${docker_compose_path}" >> $GITHUB_ENV
          else
            echo "file_exists=false" >> $GITHUB_ENV
            echo "docker_compose_path=${docker_compose_path} for this service does not exist, so skipping image build for this service!!!"
          fi
      - name: Get build list
        id: get-build-list
        env:
          docker_compose_path: ${{ env.docker_compose_path }}
          mode: CI
        run: |
          build_list=$(bash ${{ github.workspace }}/.github/workflows/scripts/get_cicd_list.sh "${mode}" ${docker_compose_path})
          echo "build_list=${build_list}" >> $GITHUB_OUTPUT

      - name: Build Image
        if: env.file_exists == 'true'
        uses: opea-project/validation/actions/image-build@main
        with:
          work_dir: ${{ github.workspace }}
          docker_compose_path: ${{ env.docker_compose_path }}
          registry: ${OPEA_IMAGE_REPO}opea
          service_list: ${{ steps.get-build-list.outputs.build_list }}
