.PHONY: all deb clean

CXX      ?= g++
CXXFLAGS ?= -std=c++11 -O2
ARCH     := $(shell dpkg --print-architecture)
MAINT    := Eli Fulkerson <elifulkerson@gmail.com>
VERSION  := 0.6
DISTDIR  := dist
BUILDDIR := build

all: xips

xips: xips.cpp
	$(CXX) -std=c++11 -o xips xips.cpp

# Build the xips binary .deb (compiled at build time; no compiler needed on
# the target). The ips package is built separately by ips/Makefile.
.ONESHELL:
deb: xips.cpp xips.1
	@set -e
	rm -rf $(BUILDDIR)
	mkdir -p $(DISTDIR)
	$(CXX) $(CXXFLAGS) -o $(DISTDIR)/xips xips.cpp
	strip $(DISTDIR)/xips
	root="$(BUILDDIR)/xips"
	install -d "$$root/DEBIAN" "$$root/usr/bin" "$$root/usr/share/man/man1" "$$root/usr/share/doc/xips"
	install -m0755 "$(DISTDIR)/xips" "$$root/usr/bin/xips"
	gzip -9 -n -c xips.1 > "$$root/usr/share/man/man1/xips.1.gz"
	desc="$$(printf ' xips reads IP addresses, ranges, subnets and MAC addresses from stdin or\n files and transforms them: expanding ranges, summarizing into CIDR blocks,\n sorting, counting, format conversion and set operations. Supports IPv4/IPv6.\n .\n It is the transformer counterpart to the ips(1) grep-like extractor.')"
	printf 'Package: xips\nVersion: %s-1\nSection: net\nPriority: optional\nArchitecture: %s\nDepends: libc6, libgcc-s1, libstdc++6\nMaintainer: %s\nHomepage: http://www.elifulkerson.com\nDescription: %s\n%s\n' \
		"$(VERSION)" "$(ARCH)" "$(MAINT)" 'expand, summarize, sort and convert IP addresses' "$$desc" > "$$root/DEBIAN/control"
	printf 'Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: xips\nSource: http://www.elifulkerson.com\n\nFiles: *\nCopyright: %s\nLicense: see upstream\n' \
		"$(MAINT)" > "$$root/usr/share/doc/xips/copyright"
	printf 'xips (%s-1) unstable; urgency=low\n\n  * Packaged xips %s.\n\n -- %s  %s\n' \
		"$(VERSION)" "$(VERSION)" "$(MAINT)" "$$(date -R)" > "$$root/usr/share/doc/xips/changelog.Debian"
	gzip -9 -n "$$root/usr/share/doc/xips/changelog.Debian"
	dpkg-deb --root-owner-group --build "$$root" "$(DISTDIR)/xips_$(VERSION)-1_$(ARCH).deb"
	echo "Built: $(DISTDIR)/xips_$(VERSION)-1_$(ARCH).deb"

clean:
	rm -f xips $(DISTDIR)/xips
	rm -rf $(BUILDDIR)
