#!/bin/bash

FILE=$1

clean_labels() {
    echo $* | \
        sed -r -e 's/,/ /g' -e 's/ +/ /g' -e 's/^\s*//' -e 's/\s*$//' | \
        tr '[[:lower:]]' '[[:upper:]]' | \
        tr ' ' '\n' | \
        sort -u | tr '\n' ' ' | \
        sed 's/\s*$//'
}

prepare_labels() {
    clean_labels $* | sed 's/ /, /g'
}

CURRENT_LABELS=$(clean_labels $(formail -z -x X-Label < "${FILE}"))

read -e -p "Enter labels (space separated): " -i "$CURRENT_LABELS" NEW_LABELS
NEW_LABELS=$(prepare_labels $NEW_LABELS)

FILE_TMP=$(mktemp "$(basename $(readlink -f "${0}"))_XXXXXX")

if formail -z -I "X-Label: $NEW_LABELS" < "${FILE}" >> "${FILE_TMP}" && \
    cp "${FILE_TMP}" "${FILE}" ; then
    rm -f "${FILE_TMP}"
fi

exit 0
