# Simple workflow that builds wasm and publish to npm registry
name: Build and publish wasm

on:
  workflow_dispatch:
    inputs:
      release_version:
        description: 'NPM Release Version'
        required: true 
        type: string
        default: 1.0.0
      NPM_tag:
        description: 'NPM Tag'
        required: true
        type: string
        default: preview
      NPM_publish_arg:
        description: 'NPM Publish arg'
        required: false
        type: string

jobs:
  tinyusdz-wasm:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest
      - name: Instsall tools
        run: |
          sudo apt install zstd
      - name: Setup Emscripten SDK
        run: |
          git clone https://github.com/emscripten-core/emsdk.git
          cd emsdk

          ./emsdk install 4.0.9
          ./emsdk activate 4.0.9

          # Revert to 3.1.51 if there is a problem.
          ## from https://github.com/Twinklebear/webgpu-cpp-usdz/blob/main/.github/workflows/deploy-page.yml
          ## TODO: 3.1.52 has a change to WebGPU API that is incompatible
          ## with the C++ bindings I have in the repo?
          #./emsdk install 3.1.51
          #./emsdk activate 3.1.51
      - name: Configure
        run: |
          source ./emsdk/emsdk_env.sh
          cd web
          mkdir cmake-build
          cd cmake-build
          emcmake cmake .. -DCMAKE_BUILD_TYPE=MinSizeRel

      - name: Build WASM
        working-directory: ${{ github.workspace }}/web/cmake-build
        run: |
          source ../../emsdk/emsdk_env.sh
          make

      - name: Configure64
        run: |
          source ./emsdk/emsdk_env.sh
          cd web
          mkdir cmake-build64
          cd cmake-build64
          emcmake cmake .. -DCMAKE_BUILD_TYPE=MinSizeRel -DTINYUSDZ_WASM64=1

      - name: Build WASM64
        working-directory: ${{ github.workspace }}/web/cmake-build64
        run: |
          source ../../emsdk/emsdk_env.sh
          make

      - name: Prepare npm
        working-directory: ${{ github.workspace }}/web/npm
        run: |
          npm install
          npm run build

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: 'tinyusdz'
          path: ${{ github.workspace }}/web/npm/dist

      - name: Version & Publish Package
        # Setup .npmrc file to publish to npm
        uses: actions/setup-node@v4
        with:
          node-version: '20.x'
          registry-url: 'https://registry.npmjs.org'
      - run: |
          npm version --no-git-tag-version ${{ github.event.inputs.release_version }} --allow-same-version
          npm publish --access public --tag ${{ github.event.inputs.NPM_tag }} ${{ github.event.inputs.NPM_publish_arg }}
        working-directory: ${{ github.workspace }}/web/npm/dist
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
