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

parsav: parsav.t config.lua pkgdata.lua
	terra $(dbg-flags) $<
parsav.o: parsav.t config.lua pkgdata.lua
	env parsav_link=no terra $(dbg-flags) $<

clean:
	rm parsav parsav.o

dep: dep.mbedtls dep.libhttp dep.json-c
dep.mbedtls: lib/mbedtls/library/libmbedtls.a \
	lib/mbedtls/library/libmbedcrypto.a \
	lib/mbedtls/library/libmbedx509.a
dep.libhttp: lib/libhttp/lib/libhttp.a
dep.json-c: lib/libhttp/json-c.a

lib:
	mkdir $@
# parsav is designed to be fronted by a real web
# server like nginx if SSL is to be used
# caveat: libhttp is a mess. the docs are completely
# full of shit. there is no lua support as far as i
# can tell.
lib/libhttp/lib/libhttp.a: lib/libhttp
	$(MAKE) -C $< lib/libhttp.a \
		RM='rm -f' \
		CC="$(CC) -Wno-unused-result" \
		DFLAGS="-DNO_SSL -DNO_FILES -DNO_CGI -DUSE_STACK_SIZE=102400 -DUSE_IPV6"

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)
lib/libhttp: lib
	cd lib && git clone https://github.com/lammertb/libhttp.git
lib/mbedtls: lib
	cd lib && git clone https://github.com/ARMmbed/mbedtls.git
lib/json-c: lib
	cd lib && git 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/libhttp.tar.gz: lib
	$(call dlfile,https://api.github.com/repos/lammertb/libhttp/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
