PREFIX=/usr/local
CFLAGS+= -Wall -ansi -O2

INSTALL_MAN?=/usr/bin/install -o root -g wheel -m444 -c
INSTALL_SCRIPT?=/usr/bin/install -o root -g wheel -m555 -c
INSTALL_PROGRAM?=/usr/bin/install -o root -g wheel -m555 -c -s
INSTALL_DATA=/usr/bin/install -o www -g www -m440 -c

IFLAGS=-I${PREFIX}/include
LFLAGS=-L${PREFIX}/lib -lsqlite3 -lcurses

RM?=/bin/rm
CP?=/bin/cp
GZIP_CMD?=/usr/bin/gzip
SED?=/usr/bin/sed
CHMOD?=/bin/chmod
MKDIR?=/bin/mkdir -p

EXAMPLES=options.mm stacks.mm stringstack.mm fmt.mm grep.mm \
 	tables.mm sqlite.mm test.sqlite tsml2sqlite.mm tsmlquery.mm tsmltest.mm

all: mm.munger

mm.munger: mm.pre
	${SED} -e "s|%%PREFIX%%|${PREFIX}|1" mm.pre > mm.munger
	${SED} -e "s|%%PREFIX%%|${PREFIX}|1" mm.man > minimunger.man
	${CHMOD} 555 mm.munger

grep: mm.munger grep.mm options.mm runtime.c runtime.h
	./mm.munger grep.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

fmt: mm.munger fmt.mm options.mm runtime.c runtime.h
	./mm.munger fmt.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

tables: mm.munger tables.mm runtime.c runtime.h
	./mm.munger tables.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

sqlite: mm.munger sqlite.mm options.mm runtime.c runtime.h
	./mm.munger sqlite.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

tsml2sqlite: mm.munger tsml2sqlite.mm options.mm runtime.c runtime.h
	./mm.munger tsml2sqlite.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

tsmlquery: mm.munger tsmlquery.mm runtime.c runtime.h
	./mm.munger tsmlquery.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

tsmltest: tsmltest.mm mm.munger tsmlquery.mm stacks.mm runtime.c runtime.h
	./mm.munger tsmltest.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

y: y.mm mm.munger runtime.c runtime.h
	./mm.munger y.mm
	${CC} ${CFLAGS} -o $@ runtime.c ${IFLAGS} ${LFLAGS}

.PHONY: tests
tests: y grep fmt tables sqlite tsml2sqlite tsmlquery tsmltest

.PHONY: clean
clean:
	${RM} -rf *.o tmp *.core tags *~ *.gz *.1 functions.* \
	grep fmt tables sqlite tsml2sqlite tsmlquery tsmltest \
	mm.munger minimunger.man tsml.db y

.PHONY: install
install: all
	${INSTALL_SCRIPT} mm.munger ${PREFIX}/bin/minimunger
	${CP} minimunger.man minimunger.1
	${GZIP_CMD} -f minimunger.1
	${INSTALL_MAN} minimunger.1.gz ${PREFIX}/man/man1/
	${MKDIR} ${PREFIX}/share/minimunger/
	${INSTALL_DATA} runtime.h runtime.c ${EXAMPLES} ${PREFIX}/share/minimunger

.PHONY: deinstall
deinstall:
	${RM} -rf ${MANDIR}/minimunger.1.gz ${PREFIX}/bin/minimunger ${PREFIX}/share/minimunger
