# cosmicnim tasks. `just` on its own runs the demo.

so := "nim/libcosmic_ffi.so"
export REMOTE := "rickub"
export BASE_URL := "https://rickub.com/nandi/cosmicnim"
export TARGET := "x86_64-unknown-linux-gnu"

default: run

# Run the Nim demo. Needs nim/libcosmic_ffi.so (see `fetch` or `build`).
run: _have-so
    cd nim && nim c -r app.nim

# Type-check the Nim side. Needs no .so: the binding loads it lazily.
check:
    cd nim && nim check app.nim

# Build the cdylib from source into nim/ (cold builds are slow; CI is faster)
build:
    cd cosmic_ffi && cargo build --release
    cp cosmic_ffi/target/release/libcosmic_ffi.so {{so}}

# Check the Rust without producing a library.
rust-check:
    cd cosmic_ffi && cargo clippy --release -- -D warnings

fmt:
    cd cosmic_ffi && cargo fmt

# Install the .so from a release. No tag means the newest v* tag on the remote.
fetch tag="":
    #!/usr/bin/env bash
    set -euo pipefail
    tag="{{tag}}"
    if [ -z "$tag" ]; then
        # The remote is the source of truth; local tags may be stale or absent.
        tag=$(git ls-remote --tags --refs "$REMOTE" 'v*' \
              | awk -F/ '{print $NF}' | sort -V | tail -1)
        [ -n "$tag" ] || { echo "no v* tags on $REMOTE" >&2; exit 1; }
        echo "latest release is $tag"
    fi
    just fetch-url "$BASE_URL/releases/download/$tag/cosmic_ffi-$tag-$TARGET.tar.gz"

# Install the .so from an explicit asset URL.
fetch-url url:
    #!/usr/bin/env bash
    set -euo pipefail
    tmp=$(mktemp -d)
    trap 'rm -rf "$tmp"' EXIT
    curl -fsSL -o "$tmp/asset.tar.gz" "{{url}}"
    # The workflow publishes a checksum beside every tarball; use it if it is there.
    if curl -fsSL -o "$tmp/asset.sha256" "{{url}}.sha256" 2>/dev/null; then
        (cd "$tmp" && sed "s|  .*|  asset.tar.gz|" asset.sha256 | sha256sum -c -)
    else
        echo "no .sha256 alongside the asset; skipping checksum" >&2
    fi
    tar xzf "$tmp/asset.tar.gz" -C "$tmp"
    cp "$tmp"/cosmic_ffi-*/libcosmic_ffi.so {{so}}
    echo "installed {{so}}"

# Cut a release by pushing a tag with git (an API-made tag triggers no CI)
tag version:
    git tag -a "{{version}}" -m "{{version}}"
    git push "$REMOTE" "{{version}}"

clean:
    rm -rf cosmic_ffi/target nim/nimcache nim/app

_have-so:
    @test -f {{so}} || { echo "missing {{so}} -- run 'just build' or 'just fetch <url>'" >&2; exit 1; }
