#!/usr/bin/env bash
#
# As reported in
# https://github.com/notepad-plus-plus/notepad-plus-plus/issues/12417:
#
# If certain locale related environmental variables are set,
# notepad++.exe throws the exception:
#
# locale::facet::_s_create_c_locale name not valid
#
# To prevent the exception from being thrown, these environmental
# variables have to be unset.
#
# To set the localization, -L can be used, see notepad++ --help,


# determine npplocale, if one of LC_ALL LC_MESSAGES LANG is set,
# else respect notepad++'s language setting
for locale in $LC_ALL $LC_MESSAGES $LANG
do
	if [[ $locale =~ ^([a-z]{2}) ]]
	then
		# looks like a browser language code, use it
		npplocale="-L${BASH_REMATCH[1]}"
		# first match wins
		break
	fi
done

# unset npplocale if the -L argument was set explicitly
for arg in "$@"
do
	if [[ $arg =~ ^-L ]]
	then
		npplocale=""
	fi
done

# https://gcc.gnu.org/onlinedocs/libstdc++/manual/localization.html
# shows how to determine environmental variables that impact the locale
# These are (impact verified by test):
unset LANG LC_ALL LC_COLLATE LC_CTYPE LC_NUMERIC LC_MESSAGES LC_MONETARY LC_TIME

# execute notepad++ securely with expected localization
exec ${MINGW_PREFIX}/lib/notepad++/notepad++.exe $npplocale "$@"
