dotfiles/.local/bin/ensure-locales

112 lines
1.9 KiB
Shell
Executable file

#!/bin/sh
# Ensure all locales specified in ~/.config/shell/locale are installed
set -eu
LOCALES="en_US.UTF-8 de_DE.UTF-8 en_DK.UTF-8 en_IE.UTF-8"
# Because `locale -a` prints, for example, "en_US.utf8",
# and `locale.gen` wants "en_US.UTF-8" instead
_locale_present() {
norm=$(printf '%s' "$1" | tr 'A-Z' 'a-z' | tr -d '-')
locale -a 2>/dev/null | tr 'A-Z' 'a-z' | tr -d '-' | grep -qx "$norm"
}
# In most cases there should be no missing `$LOCALES`
missing=""
for l in $LOCALES; do
_locale_present "$l" || missing="$missing $l"
done
if [ -z "$missing" ]; then
echo ""
echo "All locales present"
echo ""
exit 0
fi
# If there are missing `$LOCALES`, just notify the user
# because this script most likely was run as part of `dotfiles-install`
# and therefore without root privileges
if [ "$(id -u)" != 0 ]; then
self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
echo "" >&2
echo "Missing locales:$missing" >&2
echo "" >&2
echo "Fix with: sudo $self" >&2
echo "" >&2
exit 1
fi
# Install the missing `$LOCALES`
if ! command -v locale-gen >/dev/null 2>&1; then
echo "" >&2
echo "locale-gen not found, generate manually:" >&2
echo "" >&2
for l in $missing; do
echo " localedef -i ${l%.*} -f UTF-8 $l" >&2
done
echo "" >&2
exit 1
fi
[ -f /etc/locale.gen ] || : > /etc/locale.gen
for l in $missing; do
# Uncomment existing line, or append if not present at all
esc=$(printf '%s' "$l" | sed 's/\./\\./g')
if grep -qE "^#? *$esc UTF-8" /etc/locale.gen; then
sed -i "s/^# *\($esc UTF-8\)/\1/" /etc/locale.gen
else
printf '%s UTF-8\n' "$l" >> /etc/locale.gen
fi
done
locale-gen
# verify all missing `$LOCALES` were installed
rc=0
for l in $missing; do
_locale_present "$l" || {
echo "Failed to generate: $l" >&2;
rc=1;
}
done
exit $rc