# This workflow will build a Java project with Gradle
# For more information see:
#  https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle

name: "Build"
on:
  push:
    # main is left just for emergency cases.
    branches: [ main ]
  pull_request:
    branches: [ main ]

env:
  JDK_VERSION: 21
  JDK_DISTRO: 'temurin'
jobs:
  analyze_sources:
    name: "Do we need to build the application?"
    runs-on: ubuntu-latest
    outputs:
      # Export 'filter' step check result so next step can use it.
      run_build: ${{ steps.filter.outputs.src }}

    steps:
    - name: "Install packages..."
      run: sudo apt-get install sysvbanner

      # https://github.com/marketplace/actions/checkout
    - name: "Checkout sources"
      uses: actions/checkout@v6

      # https://github.com/marketplace/actions/paths-changes-filter
    - name: "Look for changes in monitored locations"
      uses: dorny/paths-filter@v3
      id: filter
      with:
        filters: |
          src:
            - 'src/**/*.java'
            - 'src/**/*.properties'
            - '*.gradle*'
            - 'gradle.properties'
            - 'gradle/**/*.properties'
            - 'build.gradle.kts'

    - name: "WILL BUILD STEP BE RUN?"
      run: |
        found="NO"
        [[ ${{ steps.filter.outputs.src }} == 'true' ]] && found="YES"
        echo "run_build=${found}" >> $GITHUB_OUTPUT
        echo -e "\n****************************************\n"
        banner "${found}"
        echo -e "****************************************"

  # Build step.
  build:
    name: "Gradle builder"
    runs-on: ubuntu-latest
    # Will run only if analyze_sources determined it is needed.
    needs: analyze_sources
    if: needs.analyze_sources.outputs.run_build == 'true'

    steps:
    - name: "Checkout sources"
      uses: actions/checkout@v6
    - name: Set up JDK ${{ env.JDK_VERSION }} ${{ env.JDK_DISTRO }}
      uses: actions/setup-java@v5
      with:
        java-version: ${{ env.JDK_VERSION }}
        distribution: ${{ env.JDK_DISTRO }}
    - name: Cache SonarCloud packages
      uses: actions/cache@v5
      with:
        path: ~/.sonar/cache
        key: ${{ runner.os }}-sonar
        restore-keys: ${{ runner.os }}-sonar
    - name: Cache Gradle packages
      uses: actions/cache@v5
      with:
        path: ~/.gradle/caches
        key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
        restore-keys: ${{ runner.os }}-gradle
    - name: "Build with Gradle"
      run: |
       chmod +x gradlew
       ./gradlew build -x checkstyleMain -x checkstyleTest
    - name: "Run SonarQube"
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
      run: ([ -z $SONAR_TOKEN ] || [ -z $SONAR_HOST_URL ] || ./gradlew sonar)
