# nostrino - a wasm BIP157 light client and its Nostr relay bridge.
#
# The primary target is the browser: `make wasm`. The gateway is native.
# TinyGo shells out to the Go toolchain for its standard library sources; the
# fallback below picks the local install when the inherited GOROOT is empty.

GO     ?= go
TINYGO ?= tinygo
BIN    ?= bin
WASM   ?= $(BIN)/nostrino.wasm
CHANNEL ?= $(BIN)/nostrino-channel.wasm

ifeq ($(wildcard $(GOROOT)/bin/go),)
  ifneq ($(wildcard $(HOME)/.local/goroot/bin/go),)
    GOROOT := $(HOME)/.local/goroot
  endif
endif
export GOROOT
export PATH := $(GOROOT)/bin:$(PATH)

.PHONY: all build wasm channel web tinygo tinygo-bridge tinygo-neutrino test race vet fmt smoke idb-smoke serve-web clean help

all: build wasm

## build: native gateway and fixture commands with the Go toolchain
build: bridge neutrino testnode discover

bridge:
	@mkdir -p $(BIN)
	$(GO) build -o $(BIN)/nostrino-bridge ./cmd/nostrino-bridge

neutrino:
	@mkdir -p $(BIN)
	$(GO) build -o $(BIN)/nostrino-neutrino ./cmd/nostrino-neutrino

testnode:
	@mkdir -p $(BIN)
	$(GO) build -o $(BIN)/nostrino-testnode ./cmd/nostrino-testnode

discover:
	@mkdir -p $(BIN)
	$(GO) build -o $(BIN)/nostrino-discover ./cmd/nostrino-discover

## wasm: the browser light client (the primary deliverable)
wasm:
	@mkdir -p $(BIN)
	$(TINYGO) build -target wasm -o $(WASM) ./cmd/nostrino-wasm

## channel: the worker that answers a wallet's chain-data frames
channel:
	@mkdir -p $(BIN)
	$(TINYGO) build -target wasm -o $(CHANNEL) ./cmd/nostrino-channel

## web: assemble the worker demo in bin/web
web: wasm
	@mkdir -p $(BIN)/web
	cp $(WASM) $(BIN)/web/nostrino.wasm
	cp "$$($(TINYGO) env TINYGOROOT)/targets/wasm_exec.js" $(BIN)/web/wasm_exec.js
	cp web/index.html web/worker.js $(BIN)/web/
	@echo "serve: cd $(BIN)/web && python3 -m http.server 8080"

## serve-web: serve the assembled demo on 127.0.0.1:8080
serve-web: web
	cd $(BIN)/web && python3 -m http.server 8080

## tinygo: build the gateway and native client with TinyGo
tinygo: tinygo-bridge tinygo-neutrino

tinygo-bridge:
	@mkdir -p $(BIN)
	$(TINYGO) build -o $(BIN)/nostrino-bridge-tiny ./cmd/nostrino-bridge

tinygo-neutrino:
	@mkdir -p $(BIN)
	$(TINYGO) build -o $(BIN)/nostrino-neutrino-tiny ./cmd/nostrino-neutrino

## test: unit and integration tests with the Go toolchain
test:
	$(GO) test ./...

## race: the tunnel and end-to-end suites under the race detector
race:
	$(GO) test -race ./pkg/tunnel ./internal/e2e

vet:
	$(GO) vet ./...

fmt:
	$(GO) fmt ./...

## smoke: torly + test node + bridge + wasm in Node
smoke: build wasm
	WASM=$(abspath $(WASM)) ./scripts/wasm-smoke.sh

## idb-smoke: smoke plus IndexedDB persistence (needs fake-indexeddb)
idb-smoke: build wasm
	WASM=$(abspath $(WASM)) ./scripts/idb-smoke.sh

clean:
	rm -rf $(BIN)

help:
	@grep -E '^## ' $(MAKEFILE_LIST) | sed 's/## /  /'
