#!/bin/sh -e
#
# make dictionaries for spell checking
#
# Copyright (C) 2017 Masatake YAMATO
# Copyright (C) 2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

#
# Usage
#
# make-dicts.sh CTAGS_EXECUTABLE DICT_DIRECTORY
#

CTAGS=${1:-"$(pwd)/ctags --quiet --options=NONE"}
OUTDIR=${2:-$(pwd)/dictfiles}

DIRS="main parsers Makefile.am configure.ac makefiles"
for m in *.mak; do
	if ! [ "$m" = '*.mak' ]; then
	   DIRS="${DIRS} $m"
	fi
done

oname=

function print_header_for_generate_files
{
	echo "#"
	echo "# This file is automatically generated by $0"
	echo '# Do not edit manually (but this should be in our git repository)'
	echo '#'
}

#
# Make dictionaries from ctags source code
#
for d in ${DIRS}; do
	oname="GENERATED-src-$d.list"
	echo making...${OUTDIR}/${oname}
	{
		print_header_for_generate_files
		git ls-files ${d}  \
		| ${CTAGS} --kinds-'*'='*' -L - -x --_xformat='%{name}	%{extras}' --extras=+'{subword}' \
		| grep 'subword' \
		| grep -v 'anon[0-9a-f]' \
		| tr A-Z a-z \
		| grep -v '^.$' \
		| while read subword rest; do
			echo $subword
		done | sort -u
	} > ${OUTDIR}/${oname}
done

#
# Make a directory from --list-languages output
#
oname=GENERATED-option-list-languages.list
echo "making...${OUTDIR}/${oname}"
{
	print_header_for_generate_files
	${CTAGS} --list-languages | while read lang rest; do
		echo $lang
	done
}> ${OUTDIR}/${oname}

#
# Make a directory from --_dump-options output
#
oname=GENERATED-option-dump-options.list
{
	print_header_for_generate_files
	echo "making...${OUTDIR}/${oname}"
	${CTAGS} --_dump-options --_force-quit
} > ${OUTDIR}/${oname}

#
# Make a directory from --_dump-keywords output
#
rm -f ${OUTDIR}/GENERATED-option-dump-keywords-*.list.TMP
${CTAGS} --_force-initializing --_dump-keywords --_force-quit \
	| while read keyword lang; do
	oname="GENERATED-option-dump-keywords-${lang}.list"
	echo $keyword >> ${OUTDIR}/${oname}.TMP
done

for f in ${OUTDIR}/GENERATED-option-dump-keywords-*.list.TMP; do
	oname=$(dirname $f)/$(basename $f .TMP)
	echo making...${oname}
	{
		print_header_for_generate_files
		sort -u $f
	} > ${oname}
	rm $f
done

exit 0
