name: "CodeQL"

on:
  schedule:
    - cron: "30 0 * * *"
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:
jobs:
  # is required nightly build?
  # More info at https://stackoverflow.com/questions/63014786/how-to-schedule-a-github-actions-nightly-build-but-run-it-only-when-there-where
  check:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: octokit/request-action@v2.x
        id: check_last_run
        with:
          route: GET /repos/{owner}/{repo}/actions/workflows/codeql.yml/runs?per_page=1&status=success
          owner: ${{ github.repository_owner }}
          repo: kamailio
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Show last execution info
        run: |
          echo "Last daily build: ${{ fromJson(steps.check_last_run.outputs.data).workflow_runs[0].head_sha }}"
    outputs:
      last_sha: ${{ fromJson(steps.check_last_run.outputs.data).workflow_runs[0].head_sha }}
  analyze:
    needs: [check]
    if: needs.check.outputs.last_sha != github.sha
    name: Analyze
    runs-on: [self-hosted, linux, x64, codeql]
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      fail-fast: false
      matrix:
        language: [ javascript, cpp, python ]

    container:
      image: ghcr.io/kamailio/pkg-kamailio-docker:${{ github.ref_name }}-bookworm
      credentials:
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}
      volumes:
        - ${{ github.workspace }}:/code

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Configure (cpp)
        if: ${{ matrix.language == 'cpp' }}
        run: make include_modules='app_lua app_python3 cnxcc db_mysql db_postgres db_redis dialplan http_client jansson lcr ndb_redis presence presence_xml presence_dialoginfo pua pua_dialoginfo topos_redis uuid websocket xmlops' cfg

      - name: After Prepare (cpp)
        if: ${{ matrix.language == 'cpp' }}
        run: export PKG_CONFIG_PATH=$RUNNER_TEMP/usr/lib/pkgconfig:$PKG_CONFIG_PATH && echo "PKG_CONFIG_PATH=$PKG_CONFIG_PATH" >> $GITHUB_ENV

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: ${{ matrix.language }}
          queries: +security-and-quality

      - name: Autobuild
        uses: github/codeql-action/autobuild@v3
        if: ${{ matrix.language == 'javascript' || matrix.language == 'python' }}

      - name: Build cpp
        if: ${{ matrix.language == 'cpp' }}
        run: make all

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          category: "/language:${{ matrix.language }}"
