#!/bin/bash

# to add document to zanata, extract .pot with: 
# grep Key DATABASE_UI_LOCALIZATION.xml | awk -F'"' '{print "#. "$2"\n" "msgid " "\""$4"\"" "\n" "msgstr " "\"\""}' > DATABASE_UI_LOCALIZATION.pot
# then pass the .pot in poedit to merge duplication and add the Zanata header

if [[ "$#" -ne 3 ]]; then
    echo "Please pass exactly 3 parameters: the .xml, the corresponding .po and the language"
    exit 1

fi

ORIGINAL_XML="$1"
LANGUAGE="$3"
FINAL_DIR="$(pwd)/Translation/${LANGUAGE}/game_files/Databases/"
TRANS_XML=$(basename "${ORIGINAL_XML}")
TRANS_XML="${FINAL_DIR}/${TRANS_XML}"
ORIGINAL_PO="$2"
WORKDIR="/tmp/thea2/${LANGUAGE}"
TEMP_PO="/${WORKDIR}/passage.temp"
TEMP_MSGSTR="/${WORKDIR}/msgstr.temp"
TEMP_MSGID="/${WORKDIR}/msgid.temp"

#Let's work on the translated xml:
mkdir -p "${FINAL_DIR}"
mkdir -p "${WORKDIR}"
cp "${ORIGINAL_XML}" "${TRANS_XML}"

# First thing first, let's anonymize the pot and delete all email references
sed -i 's/[A-Za-z0-9._%+-]\+@[A-Za-z0-9.-]\+\.[A-Za-z]\{2,6\}//' "${ORIGINAL_PO}"

function insert_to_xml {
    sed -i "s~\(Key=\"${key}\" Val=\)\".*\"\(.*\)~\1\"${translation}\"\2~g" ${TRANS_XML}

}

for key in $(grep Key ${ORIGINAL_XML}  | awk -F'"' '{print $2}'); do
    msgstr=""
    msgid=""
    translation=""
    # We search for the exact key in the po file until we get a blank line, to get the full msgstr and the msgid
    awk -v key="${key}" '{pat="#. "key"$"} !NF{s=0}s;$0 ~ pat{ print $0; s=1 }' ${ORIGINAL_PO}  > ${TEMP_PO}

    # Extract msgstr and merge all lines into one
    awk '!NF{s=0}s;/msgstr/{ print $0; s=1 }' ${TEMP_PO} | sed -e 's/^"//' -e 's/"$//' -e 's/^msgstr "//' > ${TEMP_MSGSTR}
    msgstr=$(awk 'NR{printf "%s",$0;next;}1'  ${TEMP_MSGSTR})

    # Extract msgid and merge all lines into one
    awk '/msgid/{ s=1 }s;/msgstr/{ s=0 }' ${TEMP_PO} |grep -v "msgstr" | sed -e 's/^"//' -e 's/"$//' -e 's/^msgid "//' > ${TEMP_MSGID}
    msgid=$(awk 'NR{printf "%s",$0;next;}1'  ${TEMP_MSGID})

    # Escape special char causing problem in with sed and xml
    msgstr=${msgstr//'\n'/'\\n'}
    msgstr=${msgstr//' & '/' &amp; '}
    msgstr=${msgstr//'\"'/"&quot;"}
    msgstr=${msgstr//'&'/'\&'}

    msgid=${msgid//'\n'/'\\n'}
    msgid=${msgid//' & '/' &amp; '}
    msgid=${msgid//'\"'/"&quot;"}
    msgid=${msgid//'&'/'\&'}



    if [[ "${msgstr}" == "" ]]; then
        # if the msgstr is empty, then it's not translated yet, we use original string
        translation=${msgid}
    else
        translation=${msgstr}
    fi

    # Now we have the translation, we need to insert it to the xml file
    insert_to_xml
done

