#! /usr/bin/env bash
source bashlib

isIn() {
    local key=$1; shift

    for value
    do [[ $value = "$key" ]] && return; done
}

cd "${0%/*}/../../"

emit "Enumerating localization keys"
code=$(find Classes -type f -exec grep -o 'NSLocalizedString(@"[^"]*"' {} + | sed -n 's/.*\("[^"]*"\).*/\1/p' | sort -bu)
for l in Resources/*.lproj/Localizable.strings; do
    k=${l#*/}; k=${k%%/*}
    emit "   - Found language: ${k%.lproj}"

    lang+=( "$k" )
    lprojLocal+=( "$(sed -n '/\/\/[^"]*\[REMOTE\][^"]*$/!s/^\("[^"]*"\).*/\1/p' "$l" | sort -bu)" )
    lprojAll+=( "$(sed -n 's/^\("[^"]*"\).*/\1/p' "$l" | sort -u)" )
done

allhealthy=1
healthy=1
echo; emit "Looking for unused localization keys"
for l in "${!lang[@]}"; do
    while read; do
        (( healthy )) && emit -y "Not used in code or marked '// [REMOTE]':"
        allhealthy=0
        healthy=0
        emit -y "   ${lang[l]}: ${REPLY##*([[:space:]])} "
    done < <(comm -1 -3 <(printf '%s\n' "$code") <(printf '%s\n' "${lprojLocal[l]}"))
done
(( healthy )) && emit "No unused keys."

healthy=1
echo; emit "Looking for missing localization keys"
for l in "${!lang[@]}"; do
    chealthy=1
    while read; do
        (( chealthy )) && emit -y "Used by code:"
        allhealthy=0
        chealthy=0
        healthy=0
        emit -r "   ${lang[l]}: ${REPLY##*([[:space:]])} "
    done < <(comm -2 -3 <(printf '%s\n' "$code") <(printf '%s\n' "${lprojAll[l]}"))
    khealthy=1
    while read; do
        (( khealthy )) && emit -y "Present in other languages:"
        allhealthy=0
        khealthy=0
        healthy=0
        emit -r "   ${lang[l]}: ${REPLY##*([[:space:]])} "
    done < <(for ol in "${!lang[@]}"; do comm -1 -3 <(printf '%s\n' "${lprojAll[l]}") <(printf '%s\n' "${lprojAll[ol]}"); done | sort -bu)
done
(( healthy )) && emit "No missing keys."

echo
(( allhealthy )) && emit "All good." || emit -y "Some issues detected."
