# mad -- Michigan Algorithmic Decoder
#
# You must install ply with "make ply" before attempting to run the compiler
# Optionally, run python3 -m pip install ./ply, after which you can remove the
# repository copy.
#
# SPDX-FileCopyrightText: (C) The MADness project
# SPDX-License-Identifier: BSD-2-Clause

PREFIX      ?= /usr/local
BINDIR      ?= $(PREFIX)/bin
LIBDIR      ?= $(PREFIX)/lib
INCDIR      ?= $(PREFIX)/include
DATADIR     ?= $(PREFIX)/share
MANDIR      ?= $(DATADIR)/man

CFLAGS = -O
PYTHONPKGS = yacc.py yacc.pyc lex.py lex.pyc

VERSION=$(shell sed -n <NEWS '/^[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 ply clean check spellcheck install uninstall version dist release refresh

# Build

all: ply
	(cd libctss; make)
	(cd madhouse; make MADOPTS=$(MADOPTS) )

ply:
	if [ ! -d ply ]; then git clone git@github.com:dabeaz/ply.git; fi

libctss/libctss.a:
	(cd libctss; make)

clean:
	rm -fr *.rpm *.tar.gz parser.out parsetab.py mad.sed __pycache__ libctss/*.[oa]
	(cd doc; make clean)
	(cd libctss; make clean)
	(cd madhouse; make clean)

# Validate

check:
	@$(MAKE) -C madhouse --quiet check BINDIR=$(realpath $(CURDIR))

spellcheck:
	@spellcheck mad.adoc

#  Install/uninstall

install: mad libctss/libctss.a mad.1
	sed -e 's\../libctss\/usr/include\g' <mad >mad.sed
	chmod +x mad.sed
	cp mad.sed $(DESTDIR)$(BINDIR)/mad
	cp mad.1 $(DESTDIR)$(MANDIR)/man1
	cp libctss/ctss.h $(DESTDIR)$(INCDIR)
	cp libctss/libctss.a $(DESTDIR)$(LIBDIR)
	cp $(PYTHONPKGS) $(DESTDIR)$(LIBDIR)/python`python -V 2>&1 | cut -f 2 -d ' ' | cut -f 1-2 -d .`/site-packages/

uninstall:
	rm -f $(DESTDIR)$(BINDIR)/mad
	rm -f $(DESTDIR)$(MANDIR)/man1/mad.1
	rm -f $(DESTDIR)$(INCDIR)/ctss.h
	rm -f $(DESTDIR)$(LIBDIR)/libctss.a
	(cd $(DESTDIR)$(LIBDIR)/python`python -V 2>&1 | cut -f 2 -d ' ' | cut -f 1-2 -d .`/site-packages/; rm -f $(PYTHONPKGS))

# Export

SOURCES = README COPYING NEWS control Makefile ply mad mad.adoc libctss doc madhouse

version:
	@echo $(VERSION)

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

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

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

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

# end
