# Makefile for src
#
# SPDX-FileCopyrightText: Copyright Eric S. Raymond <esr@thyrsus.com>
# SPDX-License-Identifier: BSD-2-Clause

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

VERSION=$(shell ./src version | sed -n -e "/src: /s///p")

# 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 coverage shellcheck spellcheck fixme
.PHONY: install uninstall version dist release refresh

# Build

all: src.1

clean:
	rm -f  *~ *.1 *.html *.tar.gz coverage-data
	rm -fr .rs* typescript test/typescript htmlcov

FAQ.html: FAQ.adoc
	asciidoctor -a toc FAQ.adoc

# Validate

check: pylint shellcheck
	@./srctest | ./tapview

coverage:
	@./srctest -c coverage-data | ./tapview
	@coverage report --data-file=coverage-data | grep src
	@coverage html --data-file=coverage-data

pylint:
	@pylint --score=n src

spellcheck: *.adoc
	spellcheck local.dic *.adoc

shellcheck:
	@-shellcheck -s sh -f gcc srctest

fixme:
	@if command -v rg >/dev/null; then \
		rg --no-heading FIX''ME; \
	else \
		find . -type f -exec grep -n FIX''ME {} /dev/null \; | grep -v "[.]git"; \
	fi

# Install/uninstall

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

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/src
	install -d $(DESTDIR)$(MANDIR)
	install -d $(DESTDIR)$(MANDIR)/man1
	rm -f $(DESTDIR)$(MANDIR)/man1/src.1

# Export

SOURCES = src srctest tapview Makefile control
DOCS = README.adoc INSTALL.adoc COPYING NEWS.adoc TODO.adoc src.adoc FAQ.adoc local.dic
DISTFILES = $(SOURCES) $(DOCS) src.1

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

version:
	@echo "Internal version:" $(VERSION) "NEWS file version:" $(NEWSVERSION)

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

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

release: src-$(VERSION).tar.gz src.html FAQ.html
	@[ $(VERSION) = $(NEWSVERSION) ] || { echo "Version mismatch!"; exit 1; }
	shipper version=$(VERSION) | sh -e -x

refresh: src.html FAQ.html
	@[ $(VERSION) = $(NEWSVERSION) ] || { echo "Version mismatch!"; exit 1; }
	shipper -N -w version=$(VERSION) | sh -e -x

# End
