PREFIX?=/usr/local
LOCALBASE?=/usr/local/

BINDIR=${PREFIX}/bin
MANDIR=${PREFIX}/man/man1/
MAN3DIR=${PREFIX}/man/man3/
INCDIR=${PREFIX}/include
LIBDIR=${PREFIX}/lib
ETCDIR=${PREFIX}/etc/

INSTALL_PROGRAM?=/usr/bin/install -c -s
INSTALL_SCRIPT?=/usr/bin/install -c
INSTALL_MAN?=/usr/bin/install -c
INSTALL_DATA?=/usr/bin/install -c

RM?=/bin/rm -f
CP?=/bin/cp
MKDIR?=/bin/mkdir -p
RMDIR?=/bin/rmdir
CHMOD?=/bin/chmod
GZIP_CMD?=/usr/bin/gzip
SED?=/usr/bin/sed
LN?=/bin/ln -f

VERSION=4.5

CFLAGS+= -Wall -DVERSION=\"${VERSION}\"
LFLAGS= -lcrypto -lssl
MLFLAGS= -fpic -shared

.PHONY: all
all: multifile multifile_server libmultifile.so mclient

stack.o: stack.c
	${CC} ${CFLAGS} -c -o $@ stack.c

frameserver.o: frameserver.c
	${CC} ${CFLAGS} -c -o $@ frameserver.c

frameclient.o: frameclient.c
	${CC} ${CFLAGS} -O0 -g -c -o $@ frameclient.c

multifile: wrapper.c
	${SED} -e 's|%%PREFIX%%|${PREFIX}|g' wrapper.c > wrapper_final.c
	${CC} ${CFLAGS} -o multifile wrapper_final.c

multifile_server: multifile.c frameserver.o stack.o
	${CC} ${CFLAGS} -o $@ multifile.c frameserver.o stack.o ${LFLAGS}

mclient: mclient.c frameclient.o
	${CC} ${CFLAGS} -O0 -g -o $@ mclient.c frameclient.o -lcurses ${LFLAGS}

libmultifile.so: frameclient.c
	${CC} ${CFLAGS} ${MLFLAGS} -Wl,-soname,libmultifile.so.${VERSION} -o $@ frameclient.c

.PHONY: debug
debug: multifile.c
	${CC} ${CFLAGS} -g -O0 -o multifile multifile.c frameserver.c stack.c ${LFLAGS}

.PHONY: install
install: all
	${INSTALL_PROGRAM} multifile multifile_server ${BINDIR}
	${INSTALL_PROGRAM} mclient ${BINDIR}
	
	${INSTALL_PROGRAM} libmultifile.so ${LIBDIR}/libmultifile.so.${VERSION}
	${LN} -s libmultifile.so.${VERSION} ${LIBDIR}/libmultifile.so
	${INSTALL_DATA} frameclient.h ${INCDIR}/multifile.h

	${CP} multifile.man multifile.1
	${GZIP_CMD} -f multifile.1
	${INSTALL_MAN} multifile.1.gz ${MANDIR}

	${CP} libmultifile.man libmultifile.3
	${GZIP_CMD} -f libmultifile.3
	${INSTALL_MAN} libmultifile.3.gz ${MAN3DIR}

	${SED} -e 's|%%PREFIX%%|${PREFIX}|1' multifile.rcfile > multifile.rc
	${INSTALL_SCRIPT} multifile.rc ${ETCDIR}/rc.d/multifile

.PHONY: install-tmpfs
install-tmpfs: tmpfs.sh
	${INSTALL_SCRIPT} tmpfs.sh ${BINDIR}

.PHONY: deinstall
deinstall:
	${RM} ${BINDIR}/multifile* ${BINDIR}/mclient
	${RM} ${ETCDIR}/rc.d/multifile
	${RM} ${INCDIR}/multifile.h
	${RM} ${MANDIR}/multifile* ${MAN3DIR}/libmultifile*

.PHONY: clean
clean:
	rm -f multifile_server multifile mclient wrapper_final.c echo err *.core *.rc *.o *tmp *gz *.so *.1
