name: Build revive-wasm
on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  REVIVE_WASM_INSTALL_DIR: ${{ github.workspace }}/target/wasm32-unknown-emscripten/release
  EMSCRIPTEN_VERSION: 3.1.64

jobs:
  build-revive-wasm:
    runs-on: parity-large
    defaults:
      run:
        shell: bash
    container:
      image: paritytech/ci-unified:bullseye-1.81.0
    steps:
      - uses: actions/checkout@v4

      - name: Cache LLVM build
        id: cache-llvm
        uses: actions/cache@v3
        with:
          path: |
            llvm18.0-emscripten
          # Use a unique key based on LLVM version or configuration files to avoid cache invalidation
          key: llvm-build-${{ runner.os }}-${{ hashFiles('clone-llvm.sh', 'emscripten-build-llvm.sh') }}

      - name: Install Dependencies
        if: steps.cache-llvm.outputs.cache-hit != 'true'
        run: |
          wget https://cmake.org/files/v3.20/cmake-3.20.0-linux-x86_64.sh && chmod +x cmake-3.20.0-linux-x86_64.sh && ./cmake-3.20.0-linux-x86_64.sh --prefix=/usr/local --skip-license
          alias cmake='/usr/local/bin/cmake'
          apt-get update && apt-get install -y ninja-build
          rustup target add wasm32-unknown-emscripten
          # Install Emscripten
          git clone https://github.com/emscripten-core/emsdk.git
          cd emsdk
          ./emsdk install ${{ env.EMSCRIPTEN_VERSION }}
          ./emsdk activate ${{ env.EMSCRIPTEN_VERSION }}

      - run: |
          rustup show
          cargo --version
          rustup +nightly show
          cargo +nightly --version
          bash --version

      - name: Build LLVM
        if: steps.cache-llvm.outputs.cache-hit != 'true'
        run: |
          export EMSDK_ROOT=${PWD}/emsdk
          ./emscripten-build-llvm.sh

      - name: Use Cached LLVM
        if: steps.cache-llvm.outputs.cache-hit == 'true'
        run: |
          echo "Using cached LLVM"

      - name: Build revive
        run: |
          export LLVM_LINK_PREFIX=${PWD}/llvm18.0-emscripten
          source ./emsdk/emsdk_env.sh
          make install-wasm

      - uses: actions/upload-artifact@v4
        with:
          name: revive-wasm
          path: |
            ${{ env.REVIVE_WASM_INSTALL_DIR }}/resolc.js
            ${{ env.REVIVE_WASM_INSTALL_DIR }}/resolc.wasm
          retention-days: 1
