
# config
-include Make.config

prefix		:= /usr/local
bindir		:= $(prefix)/bin
mandir		:= $(prefix)/man/man1
mimefile	:= "/etc/mime.types"

CC		?= gcc
CFLAGS		?= -g -O2


#################################################################
# setup variables, depending on the configuration

TARGET	:= webfsd
OBJS	:= main.o request.o response.o ls.o mime.o cgi.o

CFLAGS	+= -DMIMEFILE=\"$(mimefile)\"
CFLAGS	+= -Wall -Wmissing-prototypes -Wstrict-prototypes -Wpointer-arith

# sendfile yes/no
ifneq ($(USE_SENDFILE),yes)
CFLAGS	+= -DNO_SENDFILE
endif

# threads yes/no
ifeq ($(USE_THREADS),yes)
ifeq ($(SYSTEM),linux)
CFLAGS	+= -DUSE_THREADS=1 -D_REENTRANT
LDLIBS	+= -lpthread
endif
ifeq ($(SYSTEM),freebsd)
CFLAGS	+= -DUSE_THREADS=1 -D_REENTRANT -pthread
endif
endif

# OpenSSL yes/no
ifeq ($(USE_SSL),auto)
USE_SSL	:= $(call test_header,openssl/ssl.h)
endif
ifeq ($(USE_SSL),yes)
CFLAGS	+= -DUSE_SSL=1
OBJS	+= ssl.o
LDLIBS	+= -lssl
endif

# dietlibc yes/no
ifeq ($(USE_DIET),auto)
USE_DIET := $(call test_binary,diet)
endif
ifeq ($(USE_DIET),yes)
CC	:= diet $(CC)
endif


#################################################################
# usual makefile stuff -- build the whole thing

.PHONY: all build install clean
all build: $(TARGET)

install: $(TARGET)
	mkdir -p $(bindir) $(mandir)
	install -s -m755 $(TARGET) $(bindir)
	install -m 644 webfsd.man $(mandir)/webfsd.1

$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $@ $(OBJS) $(LDLIBS)

clean:
	rm -f *~ debian/*~ *.o .*.dep

realclean distclean: clean
	rm -f $(TARGET) Make.config

%.o : %.c
	$(CC) $(CFLAGS) -Wp,-MD,.depend -c -o $@ $<
	@sed -e "s|.*\.o:|$@::|" < .depend > .$*.dep && rm -f .depend

-include .*.dep


#################################################################
# some maintaining jobs

dirname := $(shell basename `pwd`)
tarball := $(subst -,_,$(dirname).tar.gz)

tar ../$(tarball): realclean
	(cd ..; tar cvzf $(tarball) $(dirname))

rpm: ../$(tarball)
	rpm -ta $<

release: realclean
	dpkg-buildpackage -tc -rfakeroot

port: realclean
	dpkg-buildpackage -B -tc -rfakeroot

checkit: realclean
	dpkg-buildpackage -us -uc -rfakeroot
	lintian ../webfs_*.changes

size:
	wc *.c


#################################################################
# poor man's autoconf ;-)

include autoconf.mk

Make.config:
	@echo "SYSTEM       := $(call ac_uname)"		>  $@
	@echo "USE_SENDFILE := yes"				>> $@
	@echo "USE_THREADS  := no"				>> $@
	@echo "USE_SSL      := $(call ac_header,openssl/ssl.h)"	>> $@
	@echo "USE_DIET     := $(call ac_binary,diet)"		>> $@
	@echo
	@echo "Make.config written, edit if needed"
	@echo

