on:
  release:
    types: [published, edited]
  workflow_dispatch:

name: Release Runtime/Rust SDK

jobs:
  release-runtime:
    name: release-rust
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          ref: '${{ github.ref }}'

      - name: Set version
        shell: bash
        run: |
          version="${{ github.ref }}"
          if [[ "$version" = "refs/heads/main" ]]; then
            version="0.0.0-dev"
          else
            version="${version/refs\/tags\/v/}"
          fi
          sed -i -e "s/0.0.0+replaced-by-ci/${version}/g" Cargo.toml
          pyproject="$(cat extism-maturin/pyproject.toml)"
          <<<"$pyproject" >extism-maturin/pyproject.toml sed -e 's/^version = "0.0.0.replaced-by-ci"/version = "'"$version"'"/g'

      - name: Setup Rust env
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          profile: minimal
          override: true
          target: ${{ matrix.target }}

      - name: Release Rust Convert Crate
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_API_TOKEN }}
        run: |
          version=$(cargo metadata --format-version=1 | jq -r '.packages[] | select(.name == "extism") | .version')

          if ! &>/dev/null curl -sLIf https://crates.io/api/v1/crates/extism-convert/${version}/download; then
            cargo publish --manifest-path convert/Cargo.toml --allow-dirty
          else
            echo "already published ${version}"
          fi

      - name: Release Rust Manifest Crate
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_API_TOKEN }}
        run: |
          version=$(cargo metadata --format-version=1 | jq -r '.packages[] | select(.name == "extism") | .version')

          if ! &>/dev/null curl -sLIf https://crates.io/api/v1/crates/extism-manifest/${version}/download; then
            cargo publish --manifest-path manifest/Cargo.toml --allow-dirty
          else
            echo "already published ${version}"
          fi

      - name: Release Runtime
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_API_TOKEN }}
        run: |
          version=$(cargo metadata --format-version=1 | jq -r '.packages[] | select(.name == "extism") | .version')

          if ! &>/dev/null curl -sLIf https://crates.io/api/v1/crates/extism/${version}/download; then
            cargo publish --manifest-path runtime/Cargo.toml --allow-dirty
          else
            echo "already published ${version}"
          fi
