# ascii -- interactive ASCII reference
#
# SPDX-FileCopyrightText: (C) Eric S. Raymond <esr@thyrsus.com>
# SPDX-License-Identifier: BSD-2-Clause

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

CFLAGS += -O -Wall -Wextra -Werror

VERSION=$(shell sed -n <NEWS.adoc '/^[0-9]/s/:.*//p' | head -1)

# Rules

# Note: to suppress the footers with timestamps being generated in HTML,
# we use "-a nofooter".
# To debug asciidoc problems, you may need to run "xmllint --nonet --noout --valid"
# on the intermediate XML that throws an error.
.SUFFIXES: .html .adoc .1

.adoc.1:
	asciidoctor -D. -a nofooter -b manpage $<
.adoc.html:
	asciidoctor -D. -a nofooter -a webfonts! $<

.PHONY: all clean check cppcheck spellcheck reflow
.PHONY: install uninstall version dist release refresh

# Build

all: ascii ascii.1

ascii: ascii.c splashscreen.h nametable.h
	$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -DREVISION='"$(VERSION)"' ascii.c -o ascii

splashscreen.h: splashscreen
	sed <splashscreen >splashscreen.h \
		-e 's/\\/\\\\/g' \
		-e 's/"/\\"/g' \
		-e 's/.*/"&" "\\n"/'

nametable.h: nametable
	sed <nametable >nametable.h \
		-e '/^#/d' \
		-e 's/^[A-Za-z ]*: */    /' \
		-e 's/%%/    }, {/'

clean:
	rm -f ascii ascii.o splashscreen.h nametable.h
	rm -f *.tar.gz *.1 *.html

# Validate

check: cppcheck

CPPCHECKOPTS =
cppcheck: nametable.h splashscreen.h
	@cppcheck --quiet -DREVISION='"$(VERSION)"' $(CPPCHECKOPTS) ascii.c

spellcheck:
	spellcheck ascii.adoc

reflow:
	@clang-format --style="{IndentWidth: 8, UseTab: ForIndentation}" -i $$(find . -name "*.[ch]")

# Install/uninstall

install:
	install -d $(DESTDIR)$(BINDIR)
	install -m 755 ascii $(DESTDIR)$(BINDIR)/ascii
	install -d $(DESTDIR)$(MANDIR)
	install -d $(DESTDIR)$(MANDIR)/man1
	install ascii.1 $(DESTDIR)$(MANDIR)/man1/ascii.1

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/ascii
	rm -f $(DESTDIR)$(MANDIR)/man1/ascii.1

# Export

SOURCES = \
	README.adoc COPYING NEWS.adoc control Makefile \
	ascii.c ascii.adoc splashscreen nametable

version:
	@echo $(VERSION)

ascii-$(VERSION).tar.gz: $(SOURCES)
	mkdir ascii-$(VERSION)
	cp -r $(SOURCES) ascii-$(VERSION)
	tar -czf ascii-$(VERSION).tar.gz ascii-$(VERSION)
	rm -fr ascii-$(VERSION)
	ls -l ascii-$(VERSION).tar.gz

dist: ascii-$(VERSION).tar.gz

release: ascii-$(VERSION).tar.gz ascii.html
	shipper version=$(VERSION) | sh -e -x

refresh: ascii.html
	shipper -N -w version=$(VERSION) | sh -e -x

# end
