#!/usr/bin/env zsh

set -e

function translations() {
    msgFile=$1

    sed -r 's/^([^ :]+).*$/\1/' ${msgFile} \
	| sort
}

typeset -a msgFiles
msgFiles=(messages/**/*.msg)

typeset -a msgDirectories
msgDirectories=()
for msgFile (${msgFiles}); do
    if ! [[ ${msgDirectories[(ie)${msgFile:h}]} -le ${#msgDirectories} ]]; then
	msgDirectories+=(${msgFile:h})
    fi
done

for msgDirectory (${msgDirectories}); do
    typeset -a dirMsgFiles
    dirMsgFiles=()
    for msgFile (${msgFiles}); do
	if [[ ${msgFile:h} == ${msgDirectory} ]]; then
	    dirMsgFiles+=(${msgFile})
	fi
    done
    
    (
	diffDir=""
	function cleanup() {
	    cd
	    [[ -n ${diffDir} ]] && rm -rf ${diffDir}
	}
	trap cleanup EXIT
	diffDir=$(mktemp -d)

	typeset -a diffArgs
	diffArgs=()

	for msgFile (${dirMsgFiles}); do
	    translations ${msgFile} > ${diffDir}/${msgFile:t}
	    diffArgs+=(${diffDir}/${msgFile:t})
	done

	printf ">>> %s\n" ${msgDirectory}
	diff --suppress-common-lines -wB ${diffArgs}
    )
done
