# Makefile for "no" -- a leading-"no " toggler
#
# Common targets:
#   make            build the ./no executable
#   make check      build and run the test suite
#   make install    install binary + manpage under $(PREFIX) (default /usr/local)
#   make uninstall  remove the installed files
#   make deb        build a .deb that installs the program and its manpage
#   make clean      remove build artifacts

CXX      ?= g++
CXXFLAGS ?= -O2 -Wall -Wextra
PREFIX   ?= /usr/local

BINDIR    = $(DESTDIR)$(PREFIX)/bin
MANDIR    = $(DESTDIR)$(PREFIX)/share/man/man1

PROG      = no
SRC       = no.cpp
MANPAGE   = no.1

VERSION   = 0.2
MAINTAINER = Eli Fulkerson <elifulkerson@gmail.com>
ARCH     := $(shell dpkg --print-architecture 2>/dev/null || echo amd64)
DEBDIR    = $(PROG)_$(VERSION)_$(ARCH)
DEBFILE   = $(DEBDIR).deb

.PHONY: all check test clean install uninstall deb

all: $(PROG)

$(PROG): $(SRC)
	$(CXX) $(CXXFLAGS) -o $@ $<

check test: $(PROG)
	@NO=$(CURDIR)/$(PROG) sh tests/run_tests.sh

install: $(PROG)
	install -d $(BINDIR)
	install -m 0755 $(PROG) $(BINDIR)/$(PROG)
	install -d $(MANDIR)
	install -m 0644 $(MANPAGE) $(MANDIR)/$(MANPAGE)
	gzip -9 -f $(MANDIR)/$(MANPAGE)

uninstall:
	rm -f $(BINDIR)/$(PROG)
	rm -f $(MANDIR)/$(MANPAGE).gz

# Build a Debian package. Stages a clean install tree under $(DEBDIR) (with
# PREFIX=/usr, as is conventional for packaged software), drops in a DEBIAN/
# control file, then assembles the .deb with dpkg-deb.
deb: $(PROG)
	rm -rf $(DEBDIR)
	$(MAKE) install DESTDIR=$(CURDIR)/$(DEBDIR) PREFIX=/usr
	install -d $(DEBDIR)/DEBIAN
	printf 'Package: %s\nVersion: %s\nSection: utils\nPriority: optional\nArchitecture: %s\nMaintainer: %s\nDescription: toggle a leading "no " on each line of input\n no reads stdin and toggles the presence of a leading "no " on each\n line, writing the result to stdout. It can also unconditionally add\n or strip the prefix.\n' \
		"$(PROG)" "$(VERSION)" "$(ARCH)" "$(MAINTAINER)" > $(DEBDIR)/DEBIAN/control
	dpkg-deb --build --root-owner-group $(DEBDIR) $(DEBFILE)
	@echo "Built $(DEBFILE) -- install with: sudo dpkg -i $(DEBFILE)"

clean:
	rm -f $(PROG)
	rm -rf $(PROG)_*_*.deb $(PROG)_*_[0-9a-z]*/
