#!/bin/bash

cd `dirname $0`

source config

SCRIPT=`basename $0`

if [ -f ${PIDFILE} ]; then
  OLDPID=`cat ${PIDFILE}`
  STILL_RUNNING=`ps -ef | grep ${OLDPID} | grep ${SCRIPT}` || test $? = 1;
  if [ -n "${STILL_RUNNING}" ]; then
    exit 2
  fi
fi
PID=`ps -ef | grep ${SCRIPT} | head -n1 | awk ' {print $2;} '`
echo ${PID} > ${PIDFILE}

# Prepare the repository by making sure it is up to date.
cd $TRANSLATION_REPO

unescaped_files=$(mktemp)
trap 'rm -f $unescaped_files' EXIT

# For each project, fetch the new translations and commit
# if there are any changes.

for project in $PROJECTS; do

  cd $project;

  if echo "$project" | grep -Eqs '_release$|_completed$' ; then
    TX_PULL_OPTS='--mode=reviewed'
    rm -f *.po > /dev/null;
    rm -f */*.po > /dev/null;
  else
    TX_PULL_OPTS='--mode=developer'
  fi

  # Fetch new translations for this project ...
  $TX pull -a -s $TX_PULL_OPTS > /dev/null;

  if test "$project" = "fenix-torbrowserstringsxml" || test "$project" = "fenix-torbrowserstringsxml_completed"
  then
    find . -name '*.xml' -exec grep -H "[^\\]'" {} \; > "$unescaped_files"
    if ! test -z "$(cat $unescaped_files)"
    then
      cat $unescaped_files | mail -s "Unescaped files in $project" emmapeel@torproject.org boklm@torproject.org
      cd ..
      continue
    fi
  fi

  # ... add them to git ...
  git add -A . > /dev/null;
  git commit -qm "new translations in $project" > /dev/null || test $? = 1;

  # ... and push them live.
  git push -q origin $project > /dev/null;

  cd ..;
done

# Remove the pidfile again
if [ -f ${PIDFILE} ]; then
  rm ${PIDFILE}
fi

# Touch the status file, to indicate that we successfully updated translations.
touch $STATUSFILE
