.POSIX:
.SUFFIXES:
.SUFFIXES: .1 .5 .1.scd .5.scd

PREFIX?=/usr/local
BINDIR?=$(PREFIX)/bin
MANDIR?=$(PREFIX)/share/man

# Exists in GNUMake but not in NetBSD make and others.
RM?=rm -f

RMDIR_IF_EMPTY:=sh -c '\
if test -d $$0 && ! ls -1qA $$0 | grep -q . ; then \
	rmdir $$0; \
fi'

all: docs ## Build and generate files

docs: docs/aptpkg.1 docs/aptpkg.5 ## Generate docs

.1.scd.1:
	scdoc < $< > $@

.5.scd.5:
	scdoc < $< > $@

.PHONY: clean
clean: ## Remove generated files
	$(RM) docs/aptpkg.1 docs/aptpkg.5

.PHONY: help
help: ## Show this help
	@egrep -h '\s##\s' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'

.PHONY: install
install: ## Install aptpkg
	mkdir -m755 -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)/man1 $(DESTDIR)$(MANDIR)/man5
	install -m755 aptpkg $(DESTDIR)$(BINDIR)/aptpkg
	install -m644 docs/aptpkg.1 $(DESTDIR)$(MANDIR)/man1/aptpkg.1
	install -m644 docs/aptpkg.5 $(DESTDIR)$(MANDIR)/man5/aptpkg.5

.PHONY: test
test: ## Run shellcheck tests
	shellcheck aptpkg

.PHONY: uninstall
uninstall: ## Uninstall aptpkg
	$(RM) $(DESTDIR)$(BINDIR)/aptpkg
	$(RM) $(DESTDIR)$(MANDIR)/man1/aptpkg.1
	$(RM) $(DESTDIR)$(MANDIR)/man5/aptpkg.5
	${RMDIR_IF_EMPTY} $(DESTDIR)$(BINDIR)
	${RMDIR_IF_EMPTY} $(DESTDIR)$(MANDIR)