#!/bin/bash
shopt -s extglob

RECORD_DELIMITER=";"

for FILE in *.po; do
    TRANS=$(egrep -h -s -x -A 1 "^msgid \"translator-credits\"" $FILE | tail -n 1 | awk -F\" '{ print $2 }')

    # Split translator string at ";" and save the output in 
    # the array TRANSLATORS
    #
    OLD_IFS="$IFS"
    IFS="$RECORD_DELIMITER"
    read -ra TRANSLATORS <<< "$TRANS"
    IFS="$OLD_IFS"
    for TRANSL in "${TRANSLATORS[@]}"; do
	#
	# Check for errors
	# Strings are ignored and an error message is printed to STDERR
        #
	# two email addresses => entries have not been separated with ";"
	echo "$TRANSL" | egrep -sq "[^@]*@[^@]*@" >/dev/null 2>&1
	if [[ 0 -eq $? ]]; then
	    echo -e "Format error in $FILE: $TRANSL" >&2
	    continue
	fi

	# Process all remaining strings 
	#
	# extract email
	#
	EMAIL=$(expr match "$TRANSL" '.*<\(.*@[^<]*\)>.*')
	if [[ -n $EMAIL ]]; then
	    # Remove email from TRANSL string
	    TRANSL=${TRANSL/*(<)${EMAIL}*(>)/}
	else
	    echo -e "$FILE: No Value for EMAIL specified" >&2
	fi

	# extract year(s)
	# expr can only handle basic regexp, so let's use egrep here
	# the regexp catches the following occurences:
        # <DATA>, YEAR
	# <DATA>,YEAR
	# <DATA> YEAR
	# <DATA>, YEAR, YEAR
	# <DATA>,YEAR, YEAR
	# <DATA>,YEAR,YEAR
	# <DATA> YEAR, YEAR
	# <DATA> YEAR-YEAR
	# <DATA> YEAR - YEAR
	# <DATA>, YEAR-YEAR
	# <DATA>,YEAR - YEAR
	# ...
	# and the same variant with with YEAR following DATA
        YEAR=$(echo $TRANSL | egrep -o "([，, ] *[[:digit:]]{4}( *[，, -] *[[:digit:]]{4})?|^[[:digit:]]{4}( *[，, -] *)?([[:digit:]]{4})?)")
	if [[ -n $YEAR ]]; then
	    # Remove year from TRANSL string
	    TRANSL=${TRANSL/"$YEAR"/}
	    # Make YEAR pretty
	    # remove whitespace
	    YEAR=${YEAR//[[:space:]]/}
	    # remove leading nad trailing comma
	    YEAR=${YEAR/#[，,]/}
	    YEAR=${YEAR/%[，,]/}
	    # replace remaining comma between to digits with "-"
	    YEAR=${YEAR/@(，|,)/-}
	else
	    echo -e "$FILE: No Value for YEAR specified" >&2
	fi

	# The remaining string is the name
	NAME=${TRANSL/\\\n/}
	if [[ -n $NAME ]]; then
	    # remove leading and trailing spaces
	    NAME=${NAME##+([[:space:]])}
	    NAME=${NAME%%+([[:space:]])}
	else
	     echo -e "$FILE: No Value for NAME specified" >&2
	fi
	# Print the result
#	echo -n "$FILE: "
#	echo -ne "\t"
	echo -n "  <member>" 	
	[[ -n $YEAR ]] && echo -n "$YEAR, "
	[[ -n $NAME ]] && echo -n "$NAME "
	[[ -n $EMAIL ]] && echo -n "<ulink url=\"mailto:${EMAIL}\"/>"
	echo "</member>" 
    done
done

exit 0
