#!/usr/bin/env bash
#
# Append translation differences on the end of all files.  Developers should run this script 
# after changing default, so that translators can easily see what items need to be translated.
#
# This script should be run from the project root, e.g:
# $ ./tools/generateTranslationDiffs.sh
#
#####################
tmp=temp_file

cd "rtdata/languages"
if [[ $? != 0 ]]; then
	printf "%s\n" "You must run this script from the root of the project."
	exit
fi

# First thing, we want to strip default of any "!" and duplicates.
dos2unix *
grep -v '^!' default | sort -Vu > "$tmp"
mv "$tmp" "default"

printf "%s\n" "Generating differences... this may take a few minutes."

# Find all already-translated files
find . -not -iname "default" -not -iname "LICENSE" -not -iname "README" -not -iname "*.sh"  -not -iname ".*" -not -iname "$tmp" |

# For every file found
while read x; do 
	printf "%s\n" "Working on differences for $x"

  # Find every already-translated line (every line that does not start with an "!") in file "$x", then sort and copy the file to "$tmp"
	grep -v '^!' "$x" | sort -Vu > "$tmp"
  
  printf "%s\n" '' '!!!!!!!!!!!!!!!!!!!!!!!!!' '! Untranslated keys follow; remove the ! prefix after an entry is translated.' '!!!!!!!!!!!!!!!!!!!!!!!!!' '' >> "$tmp"
  
  # Now to delete the already-translated lines and add them to $tmp
	# Find every line that is not a comment
	grep -v "^#" default | while read -r 'line'
		do
      # Set "key" to be just the key, without the ";human text"
			key="${line%%;*}"
      
      # Scan the translated file $x for a translated $key
			grep -q "^$key" "$x"

      # If it did not find a translated key in $x, 
			if [[ $? != 0 ]]
				then
          # then append a "!" to the line and send it to the language file
					printf "%s\n" "!${line}" >> "$tmp"
			fi
		done

	# Replace the old file with the new one, with a section at the end for differences.
	mv "$tmp" "$x"
done

printf "%s\n" "Finished generating differences."
