name: Reusable Linux Build

on:
  workflow_call:

permissions:
  contents: read
  packages: read

jobs:
  build:
    name: Compile (${{ matrix.buildtype }})
    strategy:
      fail-fast: false
      matrix:
        buildtype: [linux-debug, linux-release]
    runs-on: ubuntu-24.04
    env:
      CC: gcc-14
      CXX: g++-14
      VCPKG_BINARY_CACHE_ACCESS: ${{ secrets.VCPKG_PACKAGES_TOKEN != '' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch') && 'readwrite' || 'read' }}
      VCPKG_BINARY_SOURCES: "clear;nuget,https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json,${{ secrets.VCPKG_PACKAGES_TOKEN != '' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch') && 'readwrite' || 'read' }};nugettimeout,600"
      VCPKG_NUGET_REPOSITORY: https://github.com/${{ github.repository }}.git
      VCPKG_NUGET_API_KEY: ${{ secrets.VCPKG_PACKAGES_TOKEN != '' && ((github.event_name == 'push' && github.ref == 'refs/heads/main') || github.event_name == 'workflow_dispatch') && secrets.VCPKG_PACKAGES_TOKEN || github.token }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Export GitHub Actions cache environment variables
        uses: actions/github-script@v9
        with:
          script: |
            core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || '');
            core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || '');

      - name: Get vcpkg baseline
        shell: bash
        run: |
          set -euo pipefail
          vcpkg_commit_id="$(grep '.builtin-baseline' vcpkg.json | awk -F: '{print $2}' | tr -d '," ')"
          echo "VCPKG_GIT_COMMIT_ID=${vcpkg_commit_id}" >> "${GITHUB_ENV}"

      - name: Install Linux dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y \
            autoconf \
            autoconf-archive \
            automake \
            ccache \
            gcc-14 \
            g++-14 \
            libgl1-mesa-dev \
            libglu1-mesa-dev \
            libltdl-dev \
            libtool \
            libtool-bin \
            libx11-dev \
            libxcursor-dev \
            libxi-dev \
            libxinerama-dev \
            libxrandr-dev \
            linux-libc-dev \
            make \
            mono-complete \
            ninja-build \
            perl \
            pkg-config
          sudo ln -sf /usr/bin/ninja /usr/bin/ninja-build
          ninja --version

      - name: CCache
        uses: hendrikmuhs/ccache-action@v1.2.23
        with:
          max-size: "1G"
          key: ccache-linux-${{ matrix.buildtype }}
          restore-keys: |
            ccache-linux

      - name: Setup vcpkg
        uses: lukka/run-vcpkg@v11
        with:
          vcpkgGitURL: "https://github.com/microsoft/vcpkg.git"
          vcpkgGitCommitId: ${{ env.VCPKG_GIT_COMMIT_ID }}

      - name: Setup NuGet for vcpkg
        env:
          NUGET_AUTH_TOKEN: ${{ env.VCPKG_NUGET_API_KEY }}
        run: |
          set -euo pipefail
          unset VCPKG_FORCE_SYSTEM_BINARIES
          nuget_path="$(vcpkg fetch nuget 2>&1 | grep -E '^/' | tail -n 1)"
          if [[ -z "${nuget_path}" || ! -f "${nuget_path}" ]]; then
            echo "Failed to locate NuGet fetched by vcpkg."
            vcpkg fetch nuget 2>&1 || true
            exit 1
          fi
          mono "${nuget_path}" sources remove -name "GitHubPackages" >/dev/null 2>&1 || true
          mono "${nuget_path}" sources add \
            -source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" \
            -storepasswordincleartext \
            -name "GitHubPackages" \
            -username "${{ github.repository_owner }}" \
            -password "${NUGET_AUTH_TOKEN}"
          mono "${nuget_path}" setapikey "${NUGET_AUTH_TOKEN}" \
            -source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json"

      - name: Run CMake
        uses: lukka/run-cmake@v10
        with:
          configurePreset: ${{ matrix.buildtype }}
          buildPreset: ${{ matrix.buildtype }}
          configurePresetAdditionalArgs: "['-DTOGGLE_BIN_FOLDER=ON', '-DOPTIONS_ENABLE_IPO=OFF']"

      - name: Run CTest
        if: matrix.buildtype == 'linux-debug'
        run: ctest --test-dir build/${{ matrix.buildtype }} --output-on-failure --parallel 2

      - name: Upload artifacts
        uses: actions/upload-artifact@v7
        with:
          name: linux-${{ matrix.buildtype }}
          path: build/${{ matrix.buildtype }}/bin/

      - name: Verify vcpkg binary cache push
        if: success() && env.VCPKG_BINARY_CACHE_ACCESS == 'readwrite'
        shell: bash
        run: |
          set -euo pipefail
          mapfile -d '' logs < <(find . -name "vcpkg-manifest-install.log" -print0)
          if [[ ${#logs[@]} -eq 0 ]]; then
            echo "No vcpkg manifest logs found." >&2
            exit 1
          fi
          if grep -Eq "to [1-9][0-9]* binary cache\(s\)" -- "${logs[@]}"; then
            exit 0
          fi
          if grep -q "to 0 binary cache(s)" -- "${logs[@]}"; then
            echo "Binary cache push reported 0 caches and no successful push was found." >&2
            exit 1
          fi
          echo "No binary cache push summary found; assuming no package was built for upload."
