#!/bin/sh

set -e

LOCALEGEN=/etc/locale.gen
LOCALES=/usr/share/i18n/locales
USER_LOCALES=/usr/local/share/i18n/locales


[ -s "$LOCALEGEN" ] || exit 0

[ "$1" = '--keep-existing' ] && KEEP=1 || KEEP=0

# Remove old locale-archive before generating new locale data
[ "$KEEP" -eq 0 ] && rm -rf /usr/lib/locale/locale-archive || :

umask 022

is_entry_ok() {
	if [ -z "$locale" ] || [ -z "$charset" ]; then
		echo "error: Bad entry '$locale $charset'"
		return 1
	fi
}

nproc="$(nproc 2>/dev/null)" || nproc=1
if [ "$nproc" -gt 1 ]; then
	mem_free=0
	while read -r k v _; do
		[ "$k" = "MemFree:"      ] && mem_free="$v"          || :
		[ "$k" = "MemAvailable:" ] && mem_free="$v" && break || :  # Prefer using MemAvailable on Linux; other Debian kernels only have MemFree
	done < /proc/meminfo || :
	mem_free=$(( mem_free / 1024 / 200 ))
	[ "$mem_free" -lt 1 ] && mem_free=1 || :
	[ "$mem_free" -lt "$nproc" ] && nproc="$mem_free" || :
	jobs=0; pids=
fi 2>/dev/null

echo "Generating locales (this might take a while)..."
while read -r locale charset; do
	if [ -z "$locale" ] || [ "${locale#\#}" != "$locale" ]; then continue; fi
	is_entry_ok || continue

	if [ "$KEEP" -eq 1 ] && PERL_BADLANG=0 perl -MPOSIX -e 'exit 1 unless setlocale(LC_ALL, $ARGV[0])' "$locale"; then continue; fi

	locale_base="${locale%%.*}"
	locale_base="${locale_base%%@*}"
	locale_at="${locale#*@}"
	[ "$locale_at" = "$locale" ] && locale_at= || locale_at="@$locale_at"
	printf "  %s.%s%s..." "$locale_base" "$charset" "$locale_at"
	[ "$nproc" -gt 1 ] && echo || :

	if [ -e "$USER_LOCALES/$locale" ]; then
		input="$USER_LOCALES/$locale"
	elif [ -e "$LOCALES/$locale" ]; then
		input="$locale"
	else
		input="$locale_base$locale_at"
		if [ -e "$USER_LOCALES/$input" ]; then
			input="$USER_LOCALES/$input"
		fi
	fi
	localedef -i "$input" -c -f "$charset" -A /usr/share/locale/locale.alias "$locale" &
	if [ "$nproc" -gt 1 ]; then
		pids="$pids$! "
		jobs=$(( jobs + 1 ))

		if [ "$jobs" -ge "$nproc" ]; then
			wait "${pids%% *}" || :
			jobs=$(( jobs - 1 ))
			pids="${pids#* }"
		fi
	else
		wait
		echo " done"
	fi
done < "$LOCALEGEN"
wait
echo "Generation complete."
