name: CI (Emscripten)

on:
  workflow_call:

env:
  CTEST_OUTPUT_ON_FAILURE: 1

jobs:
  emscripten:
    name: CI

    runs-on: ubuntu-latest
    container:
      # If you change this version, change the numbers in the cache step,
      # .github/workflows/preview-build.yml (2x) and os/emscripten/Dockerfile too.
      image: emscripten/emsdk:3.1.57

    steps:
    - name: Checkout
      uses: actions/checkout@v6

    - name: Fix dubious ownership
      run: |
        git config --global --add safe.directory ${GITHUB_WORKSPACE}

    - name: Update to modern GCC
      run: |
        apt-get update
        apt-get install -y gcc-12 g++-12
        update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-12 100
        update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-12 100

    - name: Setup cache
      uses: actions/cache@v4
      with:
        # If you change this version, change the numbers in the image configuration step,
        # .github/workflows/preview-build.yml (2x) and os/emscripten/Dockerfile too.
        path: /emsdk/upstream/emscripten/cache
        key: 3.1.57-${{ runner.os }}

    - name: Add liblzma support
      run: |
        cp ${GITHUB_WORKSPACE}/os/emscripten/ports/liblzma.py /emsdk/upstream/emscripten/tools/ports/contrib/

    - name: Build (host tools)
      run: |
        mkdir build-host
        cd build-host

        echo "::group::CMake"
        cmake .. -DOPTION_TOOLS_ONLY=ON
        echo "::endgroup::"

        echo "::group::Build"
        echo "Running on $(nproc) cores"
        cmake --build . -j $(nproc) --target tools
        echo "::endgroup::"

    - name: Install GCC problem matcher
      uses: ammaraskar/gcc-problem-matcher@master

    - name: Build
      run: |
        mkdir build
        cd build

        echo "::group::CMake"
        emcmake cmake .. -DHOST_BINARY_DIR=../build-host
        echo "::endgroup::"

        echo "::group::Build"
        echo "Running on $(nproc) cores"
        cmake --build . -j $(nproc) --target openttd
        echo "::endgroup::"
