# -*- coding: cp852 -*-
# makefile for MsSocket Wrapper
# by Tomasz Zbroek / Upos System Sp. z o.o.

# read project version
VER_MAJOR := $(shell cut -d . -f 1 -s version)
VER_MINOR := $(shell cut -d . -f 2 -s version)

DEPPATH = dep
RELEASEPATH = bin
DEBUGPATH = bin/debug
OBJPATH = bin/debug/obj
SRCPATH = src test

LIBNAME = libmsock.a
ARCHIVEFILENAME = msock$(VER_MAJOR)$(VER_MINOR)s

vpath %.c src test test\windows
vpath %.h src inc
vpath %.o $(OBJPATH)
vpath %.a $(DEBUGPATH)
vpath %.exe $(DEBUGPATH)
vpath %.d $(DEPPATH)

CC = gcc

BROWSEFILES = \
	$(wildcard src/*.c src/*.h) \

SOURCES = \
	locater.c \
	netaddr.c \
	socket.c \
	drventry.c

CFLAGS = -g -I src -I inc

all : $(LIBNAME) release tags

.PHONY : test
test : listen.exe select.exe datagram.exe send.exe

.PHONY : wtest
wtest : wsend.exe wsendto.exe

# ---

$(OBJPATH)/%.o : %.c
	$(CC) -c $(CFLAGS) $< -o $@

$(DEPPATH)/%.d : %.c
	@set -e; rm -f $@; \
	$(CC) -MM $(CFLAGS) $< > $(basename $@).$$$$; \
	sed 's,\($*\)\.o[ :]*,$(OBJPATH)/\1.o $@ : ,g' < $(basename $@).$$$$ > $@; \
	rm -f $(basename $@).$$$$

# ---

$(DEBUGPATH)/$(LIBNAME) : $(SOURCES:.c=.o)
	ar rv $@ $^

include $(addprefix $(DEPPATH)/, $(SOURCES:.c=.d))

# ---

.PHONY : release
release : $(LIBNAME)
	cp $< $(RELEASEPATH)/$(LIBNAME)
	strip -s $(RELEASEPATH)/$(LIBNAME) 

.PHONY : install
install : release
	cp bin/$(LIBNAME) $(DJDIR)/lib
	cp inc/sockdefs.h $(DJDIR)/include
	cp inc/sys/socket.h $(DJDIR)/include/sys
	cp inc/netinet/in.h $(DJDIR)/include/netinet

# ---

$(DEBUGPATH)/listen.exe : listen.c $(LIBNAME)
	$(CC) $(CFLAGS) $^ -o $@

$(DEBUGPATH)/select.exe : select.c $(LIBNAME)
	$(CC) $(CFLAGS) $^ -o $@

$(DEBUGPATH)/datagram.exe : datagram.c $(LIBNAME)
	$(CC) $(CFLAGS) $^ -o $@

$(DEBUGPATH)/send.exe : send.c $(LIBNAME)
	$(CC) $(CFLAGS) $^ -o $@

$(DEBUGPATH)/wsend.exe : wsend.c 
	mingw32-gcc $(CFLAGS) $< -l ws2_32 -o $@

$(DEBUGPATH)/wsendto.exe : wsendto.c 
	mingw32-gcc $(CFLAGS) $< -l ws2_32 -o $@

# ---

.PHONY : prjfiles
prjfiles : 
	rm -f prjfiles
	find inc -type f ! -name '#*#' -a ! -name '*~' -a ! -name '*.scc' >> prjfiles
	find src -type f ! -name '#*#' -a ! -name '*~' -a ! -name '*.scc' >> prjfiles
	find doc -type f ! -name '#*#' -a ! -name '*~' -a ! -name '*.scc' >> prjfiles
	find test -type f ! -name '#*#' -a ! -name '*~' -a ! -name '*.scc' >> prjfiles
	find . -maxdepth 1 -type f ! -name '#*#' -a ! -name '*~' -a ! -name '*.scc' -a ! -name '*.gz' -a ! -name '*.zip'>> prjfiles

.PHONY : zip
zip: prjfiles
	7z a -tzip $(ARCHIVEFILENAME).zip @prjfiles

.PHONY : tar
tar: prjfiles
	tar -cz -f $(ARCHIVEFILENAME).tgz --files-from=prjfiles

# ---

tags: $(BROWSEFILES) 
	etags $^

.PHONY : dox
dox:
	doxygen doc/Doxyfile

# ---

.PHONY : clean
clean :
	-rm -f $(DEPPATH)/*
	-rm -f $(DEBUGPATH)/obj/*
	-rm -f $(DEBUGPATH)/*


