#
# CI for running tests
#

on: [push]
name: Automated Tests

jobs:
  run-tests-linux:
    runs-on: ubuntu-24.04
    steps:
    - name: Checkout
      uses: actions/checkout@v6
    - name: Install dependencies
      run: |
        sudo apt-get -y update
        sudo apt-get -ym install libbz2-dev zlib1g-dev libpng-dev autoconf clang-18 ccache moreutils
    - name: Cache
      uses: actions/cache@v4
      with:
        path: ~/.ccache
        key: ccache:${{ github.job }}:${{ github.ref }}:${{ github.sha }}
        restore-keys: |
          ccache:${{ github.job }}:${{ github.ref }}
          ccache:${{ github.job }}
    - name: Configure Simutrans Build
      run: |
        autoconf
        CC="ccache clang" CXX="ccache clang++" ./configure
        echo "FLAGS += -Wno-cast-align" >> config.default
        echo "FLAGS += -fsanitize=address,undefined -fno-sanitize-recover=all -fno-sanitize=shift,function" >> config.default
        echo "LDFLAGS += -fsanitize=address,undefined" >> config.default
        echo "STATIC := 0" >> config.default
    - name: Build Simutrans
      run: |
        CC="ccache clang" CXX="ccache clang++" make -j$(nproc)
    - name: Install pak64
      run: |
        pushd simutrans
        ../tools/get_pak.sh pak64
        popd
    - name: Install language files
      run: tools/get_lang_files.sh
    - name: Link tests as scenario
      run: |
        mkdir -p ~/simutrans/addons/pak/scenario
        ln -sT $GITHUB_WORKSPACE/tests ~/simutrans/addons/pak/scenario/automated-tests
    - name: Create simuconf
      run: |
        mkdir -p ~/simutrans/
        echo "frames_per_second = 100"              >> ~/simutrans/simuconf.tab
        echo "fast_forward_frames_per_second = 100" >> ~/simutrans/simuconf.tab
    - name: Run tests
      run: |
        export ASAN_OPTIONS="print_stacktrace=1 abort_on_error=1 detect_leaks=0"
        export UBSAN_OPTIONS="print_stacktrace=1 abort_on_error=1"
        cp tools/run-automated-tests.sh .
        chmod +x run-automated-tests.sh
        ulimit -St 600 # 10 minutes ought to be enough for anybody.
        ./run-automated-tests.sh
    - name: Run NWC protocol e2e suite
      # Black-box wire-protocol tests: spawn a headless server, send
      # one hand-rolled packet, parse the reply.  Pins NWC_AUTH_PLAYER
      # / NWC_TOOL / NWC_SERVICE request and reply shapes and acts as
      # a regression tripwire for the network security class.  Same
      # ASAN/UBSAN config as the scenario suite — a sanitizer hit
      # fails the job loudly.
      run: |
        export ASAN_OPTIONS="print_stacktrace=1 abort_on_error=1 detect_leaks=0"
        export UBSAN_OPTIONS="print_stacktrace=1 abort_on_error=1"
        python3 -m unittest discover -v -s tools/nwc_protocol_test -t .
