include config.mk

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

EFILES=mplex

# Default
.PHONY: all
all: $(EFILES) mplex.1

# Top-level targets
mplex: mplex.o epoll.o options.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 mplex.1 $(MAN)/man1/

uninstall:
	rm -f $(addprefix $(BIN)/,$(EFILES))
	rm -f $(addprefix $(MAN)/,man1/mplex.1)

# 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)
