include config.mk

CC=gcc
CFLAGS+= -std=c99 -pedantic -Wall -Wextra -Wno-unused -Werror -D_GNU_SOURCE
LDFLAGS+= -lzmq

EFILES=zmq-publish-server zmq-request zmq-subscribe zmq-publish
MANFILES=

# Default
.PHONY: all
all: $(EFILES) $(MANFILES)

# Top-level targets
zmq-publish-server: zmq-publish-server.o util.o zmqutil.o
zmq-request: zmq-request.o util.o zmqutil.o
zmq-subscribe: zmq-subscribe.o util.o zmqutil.o
zmq-publish: zmq-publish.o util.o zmqutil.o

# Man pages
%.1: %.pod
	pod2man -c '' -r '' $< > $@

%.html: %.pod Makefile
	sed -re 's/L<([a-zA-Z_]+[a-zA-Z0-9_]*)\([0-9]\)>/C<\1>/g' $< \
		| pod2html --noindex \
		| sed -re 's/<link rev="made"[^>]*>//' > $@
	rm pod2htm[di].tmp

# If we change the config or the Makefile, we need to rebuild.
*.o: %.o: config.mk Makefile

# Installation
.PHONY: install uninstall

install: all
	install -m 755 $(STRIP) $(EFILES) $(BIN)
	install -m 644 $(MANFILES) $(MAN)/man1/

uninstall:
	rm -f $(addprefix $(BIN)/,$(EFILES))
	rm -f $(addprefix $(MAN)/man1/,$(MANFILES))

# Cleanup
.PHONY: clean

clean:
	rm -f $(EFILES) *.o *.1 *.html

# Dependencies
# Empty dep files indicate a deleted source file; we should get rid of them.
$(shell find . -name '*.dep' -empty -print0 | xargs -0 rm -f)

%.dep: %.c
	set -e; $(CC) -MM -MT $< $(filter-out -pedantic,$(CFLAGS)) $< | sed 's,\($*\)\.c *:,\1.o $@ :,' > $@

CFILES=$(shell find . -name '*.c')
include $(CFILES:.c=.dep)
