CC     ?= cc
CFLAGS ?= -Wall -O2 -g
PREFIX ?= /usr/local
BINDIR ?= ${PREFIX}/bin
MANDIR ?= ${PREFIX}/share/man/man1

NGCFG_VERSION=2.1

all: bin doc
bin: nginx-confgen
doc: nginx-confgen.1

nginx-confgen: nginx-confgen.c Makefile
	${CC} ${CFLAGS} -DNGCFG_VERSION='"${NGCFG_VERSION}"' $< -o $@

nginx-confgen.1: nginx-confgen.pod Makefile
	pod2man --center "nginx-confgen manual" --release nginx-confgen-${NGCFG_VERSION} $< >$@

test: bin
	cd test && e=0 && for i in *.conf; do\
			f=`basename $$i .conf`;\
			../nginx-confgen -I inc -i $$i >$$f.out 2>&1;\
			[ ! -f $$f.test ] && cp $$f.out $$f.test;\
			d="`diff -u $$f.test $$f.out`";\
			if [ -n "$$d" ]; then echo; echo "$$d"; echo; e=1; fi;\
		done; exit $$e

test-valgrind: bin
	cd test && for i in *.conf; do\
			valgrind -q --error-exitcode=2 --log-file=valgrindlog -- ../nginx-confgen -I inc -i $$i >/dev/null 2>&1;\
			if [ $$? = 2 ]; then echo; echo "FAIL at $$i"; echo; cat valgrindlog; exit 1; fi; done
	rm -f test/valgrindlog

dist:
	rm -f nginx-confgen-${NGCFG_VERSION}.tar.gz
	mkdir nginx-confgen-${NGCFG_VERSION}
	for f in `git ls-files | grep -v ^\.gitignore`; do mkdir -p nginx-confgen-${NGCFG_VERSION}/`dirname $$f`; ln -s "`pwd`/$$f" nginx-confgen-${NGCFG_VERSION}/$$f; done
	tar -cophzf nginx-confgen-${NGCFG_VERSION}.tar.gz --sort=name nginx-confgen-${NGCFG_VERSION}
	rm -rf nginx-confgen-${NGCFG_VERSION}

distcheck: dist
	tar -xzf nginx-confgen-${NGCFG_VERSION}.tar.gz
	${MAKE}  -C nginx-confgen-${NGCFG_VERSION} test
	rm -rf nginx-confgen-${NGCFG_VERSION}

clean:
	rm -f nginx-confgen nginx-confgen.1 test/*.test

distclean: clean

install: install-bin install-doc

install-bin: bin
	mkdir -p ${BINDIR}
	install -m0755 nginx-confgen ${BINDIR}/

install-doc: doc
	mkdir -p ${MANDIR}
	install -m0644 nginx-confgen.1 ${MANDIR}/

uninstall: uninstall-bin uninstall-doc

# XXX: Ideally, these would also remove the directories created by 'install' if they are empty.
uninstall-bin:
	rm -f ${BINDIR}/nginx-confgen

uninstall-doc:
	rm -f ${MANDIR}/nginx-confgen.1
