#--*- Makefile -*--

TRUNK    ?= ^/trunk
BRANCHES ?= ^/branches
RELEASES ?= ${BRANCHES}/release
PKG_NAME ?= $(shell pwd | xargs dirname | xargs basename)

.PHONY: release major minor patch

VFILE ?= .version

# The '^\#' is used instead of '^#' to circumvent a bug in older versions of
# Make (e.g GNU Make 4.2.1). However, the '^\#' sequence also causes a warning
# about a stray backslash in newer versions of grep (e.g. GNU grep 3.8) unless
# the -P option is used. Alternatively, the following Perl program may be used:
## VERSION := $(shell perl -n -e 'print unless /^\#/;' $(VFILE))
VERSION := $(shell grep -v -P '^\#' $(VFILE))

version.h: version.hin ${VFILE}
	sed 's/@VERSION@/${VERSION}/' $< > $@

src/lib/perl5/COD/ToolsVersion.pm: src/lib/perl5/COD/ToolsVersion.pmin ${VFILE}
	sed 's/@VERSION@/${VERSION}/' $< > $@

scripts/cod-tools-version: scripts/cod-tools-version.in ${VFILE}
	sed 's/@VERSION@/${VERSION}/' $< > $@
	chmod 755 $@

release:
	svn ci
	perl -lpi -e 's/\(unreleased\)/(${VERSION})/ if $$. == 1' CHANGELOG
	perl -lpi -e 's/\.\.\./${PKG_NAME}/ if $$. == 1' CHANGELOG
	svn ci -m "CHANGELOG: switching from 'unreleased' to '${VERSION}'"
	svn cp ${TRUNK} ${RELEASES}/v${VERSION} \
	   -m "Preparing version ${VERSION} for release in the release branch."
	${MAKE} patch
	echo "${PKG_NAME} (unreleased)\n\n  * ...\n" | cat - CHANGELOG \
		> CHANGELOG.$$$$.tmp; \
	mv -f CHANGELOG.$$$$.tmp CHANGELOG

major:
	awk -F. '/^#/{print} !/^#/{print $$1+1 ".0" ".0"}' \
		${VFILE} > ${VFILE}.$$$$; \
	cat ${VFILE}.$$$$ > ${VFILE}; \
	rm -f ${VFILE}.$$$$

minor:
	awk -F. '/^#/{print} !/^#/{print $$1 "." $$2+1 ".0"}' \
		${VFILE} > ${VFILE}.$$$$; \
	cat ${VFILE}.$$$$ > ${VFILE}; \
	rm -f ${VFILE}.$$$$

patch:
	awk -F. '/^#/{print} !/^#/{print $$1 "." $$2 "." $$3+1}' \
		${VFILE} > ${VFILE}.$$$$; \
	cat ${VFILE}.$$$$ > ${VFILE}; \
	rm -f ${VFILE}.$$$$

cleanAll distclean: clean-version

clean-version:
	rm -f version.h
	rm -f src/lib/perl5/COD/ToolsVersion.pm scripts/cod-tools-version
	rm -f scripts/.cod-tools-version.d
