#!/usr/bin/env bash
#
# Copyright (c) 2020
# by the GMT Team (https://www.generic-mapping-tools.org/team.html)
# See LICENSE.TXT file for copying and redistribution conditions.
#
# This script will fild all the C files of GMT core and supplemental modules,
# extract the THIS_MODULE_PURPOSE from the source files,
# and create module_core_purpose.rst_ and module_supplements_purpose.rst_
# for the documentation.
#

# Set LC_ALL to get the same sort order on Linux and macOS
export LC_ALL=C

# Set temporary directory
TMPDIR=${TMPDIR:-/tmp}

# Define paths
RSTDIR="../doc/rst/source/"
FILE_CORE_MODULE_PURPOSE="${RSTDIR}/module_core_purpose.rst_"
FILE_SUPPL_MODULE_PURPOSE="${RSTDIR}/supplements/module_supplements_purpose.rst_"

# Output purpose of core modules
grep "^#define THIS_MODULE_LIB" *.c | egrep -v '_mt|_old|_experimental' | gawk -F: '{print $1}' | sort -u > ${TMPDIR}/gmt_core_modules.lst

echo "Writing to ${FILE_CORE_MODULE_PURPOSE}"
echo ".. Automatically generated by src/gmt_make_module_purpose.sh." > ${FILE_CORE_MODULE_PURPOSE}
echo "" >> ${FILE_CORE_MODULE_PURPOSE}
while read program; do
	modern_name=`grep "^#define THIS_MODULE_MODERN_NAME" $program | gawk '{print $3}' | sed -e 's/"//g'`
	classic_name=`grep "^#define THIS_MODULE_CLASSIC_NAME" $program | gawk '{print $3}' | sed -e 's/"//g'`
	purpose=`grep '^#define THIS_MODULE_PURPOSE' $program | gawk -F'\t' '{print $2}' | sed -e 's/^"//' -e 's/"$//'`
	echo ".. |${modern_name}_purpose| replace:: ${purpose}" >> ${FILE_CORE_MODULE_PURPOSE}
	echo "" >> ${FILE_CORE_MODULE_PURPOSE}
	if [ "$modern_name" != "$classic_name" ]; then
		echo ".. |${classic_name}_purpose| replace:: ${purpose}" >> ${FILE_CORE_MODULE_PURPOSE}
		echo "" >> ${FILE_CORE_MODULE_PURPOSE}
	fi
done < ${TMPDIR}/gmt_core_modules.lst
rm -f ${TMPDIR}/gmt_core_modules.lst

echo "Writing to ${FILE_SUPPL_MODULE_PURPOSE}"
echo ".. Automatically generated by src/gmt_make_module_purpose.sh." > ${FILE_SUPPL_MODULE_PURPOSE}
echo "" >> ${FILE_SUPPL_MODULE_PURPOSE}
# Output purpose of supplemental modules
grep "^#define THIS_MODULE_LIB" */*.c | egrep -v '_mt|_old|_experimental' | gawk -F: '{print $1}' | sort -u > ${TMPDIR}/gmt_supplements_modules.lst

while read program; do
	modern_name=`grep "^#define THIS_MODULE_MODERN_NAME" $program | gawk '{print $3}' | sed -e 's/"//g'`
	classic_name=`grep "^#define THIS_MODULE_CLASSIC_NAME" $program | gawk '{print $3}' | sed -e 's/"//g'`
	purpose=`grep '^#define THIS_MODULE_PURPOSE' $program | gawk -F'\t' '{print $2}' | sed -e 's/^"//' -e 's/"$//'`
	echo ".. |${modern_name}_purpose| replace:: ${purpose}" >> ${FILE_SUPPL_MODULE_PURPOSE}
	echo "" >> ${FILE_SUPPL_MODULE_PURPOSE}
	if [ "$modern_name" != "$classic_name" ]; then
		echo ".. |${classic_name}_purpose| replace:: ${purpose}" >> ${FILE_SUPPL_MODULE_PURPOSE}
		echo "" >> ${FILE_SUPPL_MODULE_PURPOSE}
	fi
done < ${TMPDIR}/gmt_supplements_modules.lst
rm -f ${TMPDIR}/gmt_supplements_modules.lst

echo "Writing done"
