name: emscripten

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]
  workflow_dispatch:

env:
  CPM_SOURCE_CACHE: ${{ github.workspace }}/cpm-cache

jobs:
  build-emscripten:
    runs-on: ubuntu-latest
    container: archlinux:base-devel
    steps:
    - name: Install dependencies
      run: pacman -Syu --noconfirm && pacman -S --noconfirm --needed cmake git unzip python ninja zstd nodejs
    - name: Setup emscripten
      uses: emscripten-core/setup-emsdk@v16
      with:
        version: 5.0.7
    - name: Trust git repo
      run: git config --global --add safe.directory '*'
    - uses: actions/checkout@v4
    - name: Cache CPM packages
      uses: actions/cache@v4
      with:
        path: ${{ env.CPM_SOURCE_CACHE }}
        key: ${{ runner.os }}-cpm-${{ hashFiles('**/vendor.cmake', '**/CMakeLists.txt') }}
        restore-keys: ${{ runner.os }}-cpm-
    - name: Profiler GUI
      run: |
        cmake -G Ninja -B profiler/build -S profiler -DCMAKE_BUILD_TYPE=MinSizeRel -DGIT_REV=${{ github.sha }} -DCMAKE_TOOLCHAIN_FILE=${{env.EMSDK}}/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake
        cmake --build profiler/build --parallel
    - name: Compress artifacts
      run: |
        zstd -18 profiler/build/tracy-profiler.js profiler/build/tracy-profiler.wasm
        gzip -9 profiler/build/tracy-profiler.js profiler/build/tracy-profiler.wasm
    - name: Find Artifacts
      id: find_artifacts
      run: |
        mkdir -p bin
        cp profiler/build/index.html bin
        cp profiler/build/favicon.svg bin
        cp profiler/build/tracy-profiler.data bin
        cp profiler/build/tracy-profiler.js.gz bin
        cp profiler/build/tracy-profiler.js.zst bin
        cp profiler/build/tracy-profiler.wasm.gz bin
        cp profiler/build/tracy-profiler.wasm.zst bin
    - uses: actions/upload-artifact@v4
      with:
        name: emscripten
        path: bin
  deploy:
    runs-on: ubuntu-latest
    needs: build-emscripten
    if: github.ref == 'refs/heads/master'
    steps:
    - uses: actions/download-artifact@v4
    - uses: wlixcc/SFTP-Deploy-Action@v1.2.4
      with:
        username: ${{ secrets.USERNAME }}
        server: ${{ secrets.SERVER }}
        port: ${{ secrets.PORT }}
        ssh_private_key: ${{ secrets.PRIVATE_KEY }}
        local_path: './emscripten/*'
        remote_path: ${{ secrets.REMOTE_PATH }}
        sftp_only: true