prefix=/opt/diet
BINDIR=${prefix}/bin

TARGETS=ncp

all: $(TARGETS)

CC=gcc
CFLAGS=-pipe -Wall
LDFLAGS=

path = $(subst :, ,$(PATH))
diet_path = $(foreach dir,$(path),$(wildcard $(dir)/diet))
ifeq ($(strip $(diet_path)),)
ifneq ($(wildcard /opt/diet/bin/diet),)
DIET=/opt/diet/bin/diet
else
DIET=
endif
else
DIET:=$(strip $(diet_path))
endif

# to build without diet libc support, use $ make DIET=
# see http://www.fefe.de/dietlibc/ for details about the diet libc

ifneq ($(DEBUG),)
CFLAGS+=-g
LDFLAGS+=-g
else
CFLAGS+=-O2 -fomit-frame-pointer
LDFLAGS+=-s
ifneq ($(DIET),)
DIET+=-Os
endif
endif

LDLIBS=-lowfat

libowfat_path = $(strip $(foreach dir,../libowfat*,$(wildcard $(dir)/textcode.h)))
ifneq ($(libowfat_path),)
CFLAGS+=$(foreach fnord,$(libowfat_path),-I$(dir $(fnord)))
LDFLAGS+=$(foreach fnord,$(libowfat_path),-L$(dir $(fnord)))
endif

CC:=$(DIET) $(CC)

npush: ncp
	ln -s ncp npush

npoll: ncp
	ln -s ncp npoll

ncp: ncp.o libsocket
	$(CC) $< -o $@ -I. $(CFLAGS) $(LDFLAGS) $(LDLIBS) `cat libsocket`
ifeq ($(DEBUG),)
	strip -R .note -R .comment ncp || strip ncp
endif

install:
	install -d $(PREFIX)/bin $(PREFIX)/man/man1
	install ncp $(PREFIX)/bin
	ln -f $(PREFIX)/bin/ncp $(PREFIX)/bin/npush
	ln -f $(PREFIX)/bin/ncp $(PREFIX)/bin/npoll
	install -m 644 ncp.1 npush.1 $(PREFIX)/man/man1

uninstall:
	rm -f $(PREFIX)/bin/ncp $(PREFIX)/bin/npush $(PREFIX)/bin/npoll $(PREFIX)/man/man1/ncp.1 $(PREFIX)/man/man1/npush.1

clean:
	rm -f *.o ncp core *~ *.bak npush npoll libsocket

libsocket: trysocket.c
	if $(DIET) $(CC) $(CFLAGS) -o trysocket trysocket.c >/dev/null 2>&1; then echo ""; else \
	if $(DIET) $(CC) $(CFLAGS) -o trysocket trysocket.c -lsocket >/dev/null 2>&1; then echo "-lsocket"; else \
	if $(DIET) $(CC) $(CFLAGS) -o trysocket trysocket.c -lsocket -lnsl >/dev/null 2>&1; then echo "-lsocket -lnsl"; \
	fi; fi; fi > libsocket
	rm -f trysocket

