name: Publish cargo snapshots

on:
  workflow_call:
    inputs:
      ref:
        description: "git ref to checkout to"
        type: string
        default: "master"
      cargo-dependencies:
        description: "Cargo dependencies map"
        type: string
        default: "null"
    outputs:
      version:
        description: "crate snapshots version"
        value: ${{ jobs.snapshots.outputs.version }}

jobs:
  snapshots:
    name: "Publish crates"
    runs-on: builder
    timeout-minutes: 60

    env:
      RUSTFLAGS: "-D warnings"
      RUSTC_WRAPPER: "sccache"

    outputs:
      version: "${{ steps.snapshot.outputs.version }}"

    permissions:
      contents: read
      id-token: write

    steps:
      - name: Checkout AquaVM
        uses: actions/checkout@v4
        with:
          repository: fluencelabs/aquavm
          ref: ${{ inputs.ref }}

      - name: Import secrets
        uses: hashicorp/vault-action@v2.7.3
        with:
          url: https://vault.fluence.dev
          path: jwt/github
          role: ci
          method: jwt
          jwtGithubAudience: "https://github.com/fluencelabs"
          jwtTtl: 300
          exportToken: false
          secrets: |
            kv/cargo-registry/users/ci token | CARGO_REGISTRIES_FLUENCE_TOKEN

      - name: Setup Rust toolchain
        uses: dsherret/rust-toolchain-file@v1

      - name: Setup cache
        uses: Swatinem/rust-cache@v2
        with:
          cache-directories: ~/.cache/sccache
          shared-key: aquavm
          # github allows only 10GB of cache
          # so save cache only on merge to master
          # to use less space and speed up CI
          save-if: ${{ github.event_name == 'push' }}

      - name: Setup sccache
        uses: mozilla-actions/sccache-action@v0.0.3

      - name: Set dependencies
        if: inputs.cargo-dependencies != 'null'
        uses: fluencelabs/github-actions/cargo-set-dependency@main
        with:
          dependencies: ${{ inputs.cargo-dependencies }}

      - name: Download air-interpreter-wasm binary
        uses: actions/download-artifact@v3
        with:
          name: air-interpreter-wasm

      - name: Move air_interpreter_server.wasm
        run: mv air_interpreter_server.wasm crates/interpreter-wasm/

      - name: Add air-interpreter-wasm to workspace
        run: |
          sed -i '/members/a "crates/interpreter-wasm",' Cargo.toml

      - name: Generate snapshot version
        id: version
        uses: fluencelabs/github-actions/generate-snapshot-id@main

      - name: Publish crate snapshots
        id: snapshot
        uses: fluencelabs/github-actions/cargo-publish-snapshot@main
        with:
          id: ${{ steps.version.outputs.id }}
