#!/bin/sh
set -e

locale_gen=/usr/sbin/locale-gen
if ! [ -x "$(command -v $locale_gen)" ]; then
  echo 'The locale-gen binary was not found.'

  # no locale-gen binary is not an error, because the locales
  # package might be missing in (very) minimal installations
  exit 0
fi

if [ -z "$LANG" ]; then
  echo "No locale specified for locale-gen helper."
  exit 1
fi

# enable the new locale for compilation. Always prefer UTF-8
sed -i "s/^# $LANG UTF-8$/$LANG UTF-8/" /etc/locale.gen

# On systems with low specs or when many locales need to be generated,
# locale-gen will take a long time. So we run it in the background as
# transient service.
if ! /usr/bin/systemd-run -q --unit=auto-localegen $locale_gen; then
  # we could not execute locale gen (maybe it was already running?)
  # set a marker so we regenerate it next time
  /usr/bin/touch /var/lib/systemd/locale-gen-required
fi
