#!/bin/sh

if ! command -v pandoc; then
	echo '
Please install "pandoc". This tool is needed to convert markdown to man pages.
This tool is needed to convert files under docs/usage into man pages for the
installation.
'
	exit 1
fi

for i in "$(dirname "${0}")"/../docs/usage/distrobox*; do
	pandoc --standalone \
		--metadata title="$(basename "${i}" | cut -d'.' -f1 | tr '[:lower:]' '[:upper:]')" \
		--metadata section=1 \
		--metadata header="User Manual" \
		--metadata footer="Distrobox" \
		--metadata date="$(date +"%b %Y")" \
		--to man "${i}" \
		-o "$(dirname "${0}")"/man1/out
	sed -i 's|\" Automatically generated by Pandoc.*||g' "$(dirname "${0}")"/man1/out
	mv "$(dirname "${0}")/man1/out" "$(dirname "${0}")/man1/$(basename "${i}" | sed 's|md|1|g')"
done

compatibility_file="$(mktemp --suffix='.md')"
HEAD="$(grep -n -B1 "^# Compatibility" "$(dirname "${0}")/../docs/compatibility.md" | head -1 | tr -d '-')"
START="$(grep -n "# Host Distros" "$(dirname "${0}")/../docs/compatibility.md" | cut -d":" -f1)"
END="$(grep -n -B1 "# Containers Distros" "$(dirname "${0}")/../docs/compatibility.md" | head -1 | tr -d '-')"

sed -e "${START},${END}d" "$(dirname "${0}")/../docs/compatibility.md" > "${compatibility_file}"
sed -e "1,${HEAD}d" -i "${compatibility_file}"
sed -i "s/^#.*/\U&/g" "${compatibility_file}"

pandoc --standalone \
	--metadata title="DISTROBOX" \
	--metadata section=1 \
	--metadata header="User Manual" \
	--metadata footer="Distrobox" \
	--metadata date="$(date +"%b %Y")" \
	--to man "${compatibility_file}" \
	-o "$(dirname "${0}")"/man1/out
sed -i 's|\" Automatically generated by Pandoc.*||g' "$(dirname "${0}")"/man1/out
mv "$(dirname "${0}")"/man1/out "$(dirname "${0}")"/man1/distrobox-compatibility.1

cat "$(dirname "${0}")/man1/distrobox-"* > "$(dirname "${0}")/man1/distrobox.1"
