BIN      := @BIN@
LIB      := @LIB@
INCLUDE  := @INCLUDE@
SITELISP := @SITELISP@

LIB_UR   := $(LIB)/ur
LIB_C    := $(LIB)/c
LIB_JS   := $(LIB)/js

LIB_VERSION := 1:0

all: smlnj mlton c

.PHONY: all smlnj mlton c clean install package

smlnj: src/urweb.cm
mlton: bin/urweb

OBJS := memmem mhash urweb request queue http cgi fastcgi
SOS  := urweb urweb_http urweb_cgi urweb_fastcgi
c: $(OBJS:%=lib/c/%.lo) $(SOS:%=lib/c/lib%.la)

clean:
	rm -f src/*.mlton.grm.* src/*.mlton.lex.* \
		src/urweb.cm src/urweb.mlb \
		lib/c/*.o lib/c/*.so.*
	rm -rf .cm src/.cm

lib/c/%.lo: src/c/%.c include/*.h
	libtool --mode=compile gcc -Wimplicit -O3 -I include -c $< -o $@ $(CFLAGS)

LIBARGS := -rpath $(LIB)/.. -version-info $(LIB_VERSION)

URWEB_OS := memmem urweb queue request mhash
lib/c/liburweb.la: $(URWEB_OS:%=lib/c/%.lo)
	libtool --mode=link gcc -o $@ $^ $(LIBARGS)

lib/c/liburweb_%.la: lib/c/%.lo
	libtool --mode=link gcc -o $@ $^ $(LIBARGS)

src/urweb.cm: src/prefix.cm src/sources
	cat src/prefix.cm src/sources \
	>src/urweb.cm

src/urweb.mlb: src/prefix.mlb src/sources src/suffix.mlb
	cat src/prefix.mlb src/sources src/suffix.mlb \
	| sed 's/^\(.*\).grm$$/\1.mlton.grm.sig:\1.mlton.grm.sml/; y/:/\n/' \
	| sed 's/^\(.*\).lex$$/\1.mlton.lex.sml/' \
	>$@

%.mlton.lex: %.lex
	cp $< $@
%.mlton.grm: %.grm
	cp $< $@

%.mlton.lex.sml: %.mlton.lex
	mllex $<

%.mlton.grm.sig %.mlton.grm.sml: %.mlton.grm
	mlyacc $<

MLTON := mlton

ifdef DEBUG
	MLTON += -const 'Exn.keepHistory true'
endif

ifdef PROFILE
	MLTON += -profile $(PROFILE)
endif

bin/urweb: src/compiler.mlb src/urweb.mlb src/*.sig src/*.sml \
		src/urweb.mlton.lex.sml \
		src/urweb.mlton.grm.sig src/urweb.mlton.grm.sml
	$(MLTON) -output $@ src/compiler.mlb

install:
	mkdir -p $(BIN)
	cp bin/urweb $(BIN)/
	mkdir -p $(LIB_UR)
	cp lib/ur/*.urs $(LIB_UR)/
	cp lib/ur/*.ur $(LIB_UR)/
	mkdir -p $(LIB_C)
	cp lib/c/*.o $(LIB_C)/
	mkdir -p $(LIB_JS)
	cp lib/js/*.js $(LIB_JS)/
	mkdir -p $(INCLUDE)
	cp include/*.h $(INCLUDE)/
	mkdir -p $(SITELISP)
	cp src/elisp/*.el $(SITELISP)/
	libtool --silent --mode=install install -c lib/c/liburweb.la $(LIB)/../liburweb.la
	libtool --silent --mode=install install -c lib/c/liburweb_http.la $(LIB)/../liburweb_http.la
	libtool --silent --mode=install install -c lib/c/liburweb_cgi.la $(LIB)/../liburweb_cgi.la
	libtool --silent --mode=install install -c lib/c/liburweb_fastcgi.la $(LIB)/../liburweb_fastcgi.la
	libtool --silent --finish $(LIB)/../liburweb.la
	libtool --silent --finish $(LIB)/../liburweb_http.la
	libtool --silent --finish $(LIB)/../liburweb_cgi.la
	libtool --silent --finish $(LIB)/../liburweb_fastcgi.la

package:
	hg archive -t tgz -X tests /tmp/urweb.tgz
