
MAKEFLAGS += --warn-undefined-variables

cleanfiles := *.o rewrite-time

variants := lockfile-check lockfile-create lockfile-remove lockfile-touch
variants += mail-lock mail-touchlock mail-unlock

generated  := $(addprefix bin/,$(variants))
generated  += $(patsubst %,man/%.1,$(variants))
cleanfiles += $(generated)

CFLAGS := -g -Wall -Wformat-security -Werror -O2 -fwrapv -fno-strict-aliasing $(CFLAGS)
CPPFLAGS ?=
LDFLAGS ?=

.SUFFIXES:

%.o: %.c
	$(CC) $(CPPFLAGS) $(CFLAGS) -c $<
%: %.o
	$(CC) -o $@ $(LDFLAGS) $^ $(LOADLIBES) $(LDLIBS)

all: $(generated)
.PHONY: all

config.h: debian/changelog rewrite-time
	set -ex; \
	date="$$(./changelog-date)"; \
	ver="$$(./changelog-version)"; \
	echo '#pragma once' > $@.tmp; \
	echo "#define LOCKFILE_PROGS_DATE \"$$date\"" >> $@.tmp; \
	echo "#define LOCKFILE_PROGS_VERSION \"$$ver\"" >> $@.tmp; \
	mv config.h.tmp config.h
cleanfiles += config.h config.h.tmp

lockfile-progs.o: config.h

# Two independent binaries because mail-lock may need sgid, etc.
bin/lockfile-create: LOADLIBES += -llockfile
bin/lockfile-create: lockfile-progs.o
	mkdir -p bin
	$(CC) -o $@ $(LDFLAGS) $< $(LOADLIBES)
bin/mail-lock: bin/lockfile-create
	cp -p $^ $@
bin/lockfile-%: bin/lockfile-create
	ln $^ $@
bin/mail-%: bin/mail-lock
	ln $^ $@
cleandirs += bin

man/lockfile-progs.1: lockfile-progs.1.in debian/changelog rewrite-time
	mkdir -p man
	set -ex; \
	date="$$(./changelog-date)"; \
	ver="$$(./changelog-version)"; \
	sed -E -e "s/@DATE@/$$date/" -e "s/@VERSION@/$$ver/;" $< >  $@.tmp; \
	mv $@.tmp $@
cleanfiles += man/lockfile-progs.1 man/lockfile-progs.1.tmp
cleandirs += man

man/%.1: man/lockfile-progs.1
	echo .so lockfile-progs.1 > $@

# These tests are quite insufficient, but perhaps better than nothing for now.
check: all
	rm -rf check
	mkdir check

	bin/lockfile-create check/file
	bin/lockfile-touch --oneshot check/file
	bin/lockfile-check check/file
	bin/lockfile-remove check/file
	! test -e check/file.lock

	bin/lockfile-create --lock-name check/file.lock
	bin/lockfile-touch --oneshot --lock-name check/file.lock
	bin/lockfile-check --lock-name check/file.lock
	bin/lockfile-remove --lock-name check/file.lock
	! test -e check/file.lock

	bin/lockfile-create --use-pid --lock-name check/file.lock
	bin/lockfile-touch --oneshot --lock-name check/file.lock
        # PID shouldn't be the same, so this should fail.
	bin/lockfile-check --use-pid --lock-name check/file.lock
	bin/lockfile-remove --lock-name check/file.lock
	! test -e check/file.lock

	bin/lockfile-create --use-pid --lock-name check/lockfile.no-pid
.PHONY: check
cleandirs += check

clean:
	rm -f $(cleanfiles)
	rm -rf $(cleandirs)
.PHONY: clean
