#!/bin/sh

set -e

# first get all possible locales and create a full list of locale values:

TEMPFILE="$(mktemp --suffix ".locales")"
LOCALELIST=/var/cache/localepurge/localelist

# for the purpose of presenting a ready made preselection at the very first
# configuration, include already configured locales from locales package:

LOCALEGEN="$(mktemp --suffix ".locale.gen")"

if [ -f /etc/locale.gen ]; then
    grep ^[a-z] /etc/locale.gen | cut -d" " -f1 > "$LOCALEGEN"
    # add double character locale names from underscore variations
	# for later preselection:
    cut -d"_" -f1 "$LOCALEGEN" | sort -u >> "$LOCALEGEN"
fi

# if it already exists, include locales from /etc/locale.nopurge:

if [ -f /etc/locale.nopurge ]; then
    grep ^[a-z] /etc/locale.nopurge | cut -d" " -f1 >> "$LOCALEGEN"
fi

# add values from "$LOCALEGEN" to "$TEMPFILE":

cat "$LOCALEGEN" >> "$TEMPFILE"

# include locales supported by the locales package:

find /usr/share/locale -maxdepth 1 -type d -name "*" -printf "%f\n" | grep "^[a-z]" | cut -d" " -f1 | sort -u >> "$TEMPFILE"

# include locales from our previous localelist if it already exists:

if [ -f "$LOCALELIST" ]; then
    cat "$LOCALELIST" >> "$TEMPFILE"
fi

# include locales from newly added locales:
NEWLOCALELIST="$LOCALELIST"-new

if [ -f "$NEWLOCALELIST" ]; then
    cat "$NEWLOCALELIST" >> "$TEMPFILE"
    rm -f "$NEWLOCALELIST"
fi

# creating double character locale names from underscore variations:

cut -d"_" -f1 "$TEMPFILE" | sort -u >> "$TEMPFILE"

# save full list of locale values into locale list:

if [ ! -f "$LOCALELIST" ]; then
    if [ ! -d /var/cache/localepurge ]; then
	    mkdir -m 755 /var/cache/localepurge
    fi
    sort -u "$TEMPFILE" > "$LOCALELIST"
   else
    mv "$LOCALELIST" "$LOCALELIST"-old
    sort -u "$TEMPFILE" > "$LOCALELIST"
fi

# deleting temporary files not needed anymore:

rm -f "$TEMPFILE" "$LOCALEGEN"

