dl = git
dbg-flags = $(if $(dbg),-g)

images = $(addsuffix .webp, $(basename $(wildcard static/*.svg)))
styles = $(addsuffix .css, $(basename $(wildcard static/*.scss)))

parsav: parsav.t config.lua pkgdata.lua $(images) $(styles)
	terra $(dbg-flags) $<
parsav.o: parsav.t config.lua pkgdata.lua $(images) $(styles)
	env parsav_link=no terra $(dbg-flags) $<
parsav.ll: parsav.t config.lua pkgdata.lua $(images) $(styles)
	env parsav_emit_type=ll parsav_link=no terra $(dbg-flags) $<
parsav.s: parsav.ll
	llc --march=$(target) $<

static/%.webp: static/%.png
	cwebp -q 90 $< -o $@
static/%.png: static/%.svg
	inkscape -f $< -C -d 180 -e $@
static/%.css: static/%.scss
	sassc -t compressed $< $@

clean:
	rm parsav parsav.o

install: parsav
	mkdir $(prefix)/bin
	cp $< $(prefix)/bin/

dep: dep.mbedtls dep.mongoose dep.json-c
dep.mbedtls: lib/mbedtls/library/libmbedtls.a \
	lib/mbedtls/library/libmbedcrypto.a \
	lib/mbedtls/library/libmbedx509.a
dep.mongoose: lib/mongoose/libmongoose.a
dep.json-c: lib/json-c/libjson-c.a

lib:
	mkdir $@
# generate a shim static library so mongoose cooperates
# with the build apparatus. note that parsav is designed
# to be fronted by a real web server like nginx if SSL
# is to be used, so we don't turn on SSL in mongoose
lib/mongoose/libmongoose.a: lib/mongoose lib/mongoose/mongoose.c lib/mongoose/mongoose.h
	$(CC) -c $</mongoose.c -o lib/mongoose/mongoose.o \
		-DMG_ENABLE_THREADS=1 \
		-DMG_ENABLE_IPV6=1 \
		-DMG_ENABLE_HTTP_WEBDAV=1 \
		-DMG_ENABLE_HTTP_WEBSOCKET=0
	ar rcs $@ lib/mongoose/*.o
	ranlib $@

lib/json-c/Makefile: lib/json-c lib/json-c/CMakeLists.txt
	cd lib/json-c && cmake .
lib/json-c/libjson-c.a: lib/json-c/Makefile
	$(MAKE) -C lib/json-c
lib/mbedtls/library/%.a: lib/mbedtls 
	$(MAKE) -C lib/mbedtls/library $*.a

ifeq ($(dl), git)
clone = git clone --depth 1 # save time
lib/mongoose: lib
	cd lib && $(clone) https://github.com/cesanta/mongoose.git
lib/mbedtls: lib
	cd lib && $(clone) https://github.com/ARMmbed/mbedtls.git
lib/json-c: lib
	cd lib && $(clone) https://github.com/json-c/json-c.git
else
lib/%: lib/%.tar.gz
	cd lib && tar zxf $*.tar.gz
	mv lib/$$(tar tf $< | head -n1) $@

ifeq ($(dl), wget)
    dlfile = wget "$(1)" -O "$(2)"
endif

ifeq ($(dl), curl)
    dlfile = curl "$(1)" -o "$(2)"
endif

lib/mongoose.tar.gz: lib
	$(call dlfile,https://api.github.com/repos/cesanta/mongoose/tarball/master,$@)
lib/mbedtls.tar.gz: lib
	$(call dlfile,https://api.github.com/repos/ARMmbed/mbedtls/tarball/master,$@)
lib/json-c.tar.gz: lib
	$(call dlfile,https://api.github.com/repos/json-c/json-c/tarball/master,$@)
endif
