# This script produces a web build. If you aren't trying to do that, it is
# entirely useless to you.

# Patch these to select a different build profile or target
# The target shouldn't change any time soon. WASM64, I guess. Other targets
# aren't aimed at the web, so you shouldn't be using this makefile.
CARGO_TARGET := wasm32-unknown-unknown
CARGO_PROFILE := wasm-release

# Override DESTDIR to set a custom install path (such as your web root)
DESTDIR ?= .

SRC_DIR = ./src
SRCS := $(wildcard $(SRC_DIR)/**)

.PHONY: clean full-clean install tarball tarball-standalone web web-standalone

# "Standalone" version
# (i.e., it includes an index.html so it can be placed on a server as-is)
web-standalone: out/boids.js out/boids_bg.wasm.gz out/index.html

# "Bundle-able" version. The host site must provide it's own HTML page.
web: out/boids.js out/boids_bg.wasm.gz out/boids.html

tarball: boids_web_root.tar

tarball_standalone: boids_web_root_standalone.tar

boids_web_root.tar: out/boids.js out/boids_bg.wasm.gz out/boids.html
	tar -caf $@ $^

boids_web_root_standalone.tar: out/boids.js out/boids_bg.wasm.gz out/index.html
	tar -caf $@ $^

target/$(CARGO_TARGET)/$(CARGO_PROFILE)/another-boids-in-rust.wasm: $(SRCS) Cargo.lock Cargo.toml
	cargo build --profile $(CARGO_PROFILE) --target $(CARGO_TARGET)

out:
	mkdir $@

# Both the JS and WASM files are generated by the wasm-bindgen call, so both
# get to be on the target half of this recipe.
out/boids.js out/boids_bg.wasm.gz &: target/$(CARGO_TARGET)/$(CARGO_PROFILE)/another-boids-in-rust.wasm | out
	wasm-bindgen --no-typescript --target web --out-dir ./out/ --out-name boids target/$(CARGO_TARGET)/$(CARGO_PROFILE)/another-boids-in-rust.wasm
	gzip -9 -f out/boids_bg.wasm

# Copies the index page to the output
out/index.html: www/index.html
	cp -a $< $@
	rm -f out/boids.html

# Like `out/index.html`, but renames it for use in a larger site.
out/boids.html: www/index.html
	cp -a $< $@
	rm -f out/index.html

# Clean the web build, but not the Cargo cache. Cargo handles it's own caching
# and I don't want to obliterate it all the time.
clean:
	rm -rf out/ boids_web_root.tar boids_web_root_standalone.tar

# Delete everything, including the Cargo build cache. In case someone needs
# this, I guess.
full-clean: clean
	cargo clean

# Installation goal. It's meant to be a helper utility for moving the built
# output into the web root. Only supports the "bundle-able" mode.
install: web
	install -dm0755 $(DESTDIR)
	install -m0644 out/boids.js $(DESTDIR)/
	install -m0644 out/boids_bg.wasm.gz $(DESTDIR)/
	install -m0644 out/boids.html $(DESTDIR)/
