#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

SOURCE_DIRS := $(subst /,,$(dir $(wildcard **/README.md)))
MANPAGES := $(join $(SOURCE_DIRS), $(SOURCE_DIRS:%=/%.1))
RST := $(join $(SOURCE_DIRS), $(SOURCE_DIRS:%=/%.rst))
PANDOC_VERSION := $(shell pandoc --version | head -n1 | cut -d ' ' -f2)
DATE ?= $(shell date '+%Y-%m-%d')
TC_VERSION ?= $(shell cat ../VERSION)

PANDOC_FLAGS := --strip-comments

.PHONY: man rst clean

man: $(MANPAGES)

%.1: APP=$(subst /,,$(dir $@))
.SECONDEXPANSION:
%.1: $$(dir %)/README.md
	echo '.\" Automatically generated by Pandoc $(PANDOC_VERSION)' > $@
	echo '.\"' >> $@
	echo '.TH "$(APP)" "1" "$(DATE)" "$(APP) $(TC_VERSION)" "ATC t3c Manual"' >> $@
	echo '.hy' >> $@
	pandoc $(PANDOC_FLAGS) --to man $? >> $@


rst: $(RST)

%.rst: APP=$(subst /,,$(dir $@))
.SECONDEXPANSION:
%.rst: $$(dir %)/README.md
	echo ".. highlight:: text" > $@
	echo "" >> $@
	echo ".. program:: $(APP)" >> $@
	echo "" >> $@
	echo ".. _t3c-$(APP):" >> $@
	echo "" >> $@
	echo $(APP) | tr '[:alnum:]-' '*' >> $@
	echo $(APP) >> $@
	echo $(APP) | tr '[:alnum:]-' '*' >> $@
	echo "" >> $@
	pandoc $(PANDOC_FLAGS) --to rst $? >> $@


clean:
	$(RM) $(MANPAGES) $(RST)
