#!/bin/bash

RED='\033[0;31m'
NC='\033[0m' # No Color

rm -rf spelling
mkdir spelling
# Get names of all actions and command line tools
../src/lib/plumed --no-mpi manual --action=ABMD > /dev/null 2> spelling/keywords
cat spelling/keywords | grep -v "LIST OF" | awk '{if(NF>0) print $1}' > spelling/pkeys
# Get all the keywords for all actions
while read flag; do
   ../src/lib/plumed --no-mpi manual --action=$flag --spelling > spelling/$flag.psp 2> /dev/null
   cat spelling/$flag.psp | sed -e $'s/_/\\\n/g' | sed -e $'s/-/\\\n/g' | grep -v '[0-9]' | grep -v "help" | awk '{if(NF>0) print $1}' >> spelling/allkeys 
done < spelling/pkeys
# Now reconfigure the keyword list to get rid of troublesome characters
cat spelling/pkeys | sed -e $'s/_/\\\n/g' | grep -v '[0-9]' | sed -e $'s/-/\\\n/g' > spelling/keywords
# And now construct the exclude list for the spell checker
nsafewords=`cat spelling/keywords spelling/allkeys spelling_words.dict | wc -l | awk '{print $1}'`
echo personal_ws-1.1 en $nsafewords > ./spelling/allwords.dict
cat spelling/keywords spelling/allkeys spelling_words.dict >> spelling/allwords.dict
# Get the git version
git_version="$(../src/lib/plumed --no-mpi info --git-version)"

# This is everything we have done thus far
for file in *PP.md automatic/*.txt ../CHANGES/*.md tutorials/*.txt tutorials/*.site tutorials/others/*.txt ; do
    # echo Checking spelling for file $file
    splits=`echo $file | sed -e 's/\// /g'`
    nf=`echo $splits | awk '{print NF}'`
    fname=`echo $splits | awk -v n=$nf '{print $n}'` 
    # This is some stuff to get rid of stuff that trips up the spell checker: the equations and the plumed examples 
    cat $file | grep -v "\\image" | grep -v $git_version | grep -v "anchor" | sed -e 's/psi-1//' | sed -e 's/-#//' | sed -e 's/@//' | sed -e 's/&//' | sed -e 's/\vdots//' | 
    awk 'BEGIN{inp=0}{
          if($1=="\\endplumedfile" || $1=="\\f]" || $1=="\\f}" || $1=="\\endauxfile" || $1=="\\endverbatim" || $1=="\\endcode"){inp=0;}
          else if($1=="\\plumedfile" || $1=="\\f[" || $1=="\\f{eqnarray*}{" || $1=="\\f{align}{" || match($1,"auxfile") || $1=="\\verbatim" || index($1,"\\code{")!=0 ){inp=1;}
          else if(inp==0){
            skip=0;
            for(i=1;i<=NF;++i){ 
                if(skip==1){ skip=0; }
                else if($i=="\\subsubsection" || $i=="\\cite" || $i=="\\ref" || $i=="\\page" || $i=="subpage" || $i=="\\subpage" || $i=="\\section" || $i=="\\subsection" || $i=="\\link" ){ skip=1; }
                else if(index($i, "\\f$")==0 && index($i,"http")==0 && index($i,".py")==0 ) { printf(" %s",$i); }
            }
            printf("\n");
          }
          }' > spelling/$fname.md

    # Check for spelling mistakes
    tail -n +2 spelling/$fname.md | grep -v "*/" | aspell pipe -H --dont-suggest --personal=./spelling/allwords.dict | grep -v '*' | grep -v "International Ispell" | awk '{if(NF>0) print $0}' > spelling/$fname.err
    nerrors=`wc -l spelling/$fname.err | awk '{print $1}'`
    # Crash out if there are spelling mistakes
    if [ $nerrors -gt 0 ] ; then 
       echo -n "Found spelling mistakes in documentation file $file<< \\n " >> spelling_results
       cat spelling/$fname.err | awk '{printf("%s ", $2)}' >> spelling_results
       echo -n "\\n " >> spelling_results
    fi
done

# Test for existance of spelling results
if [ ! -f spelling_results ] ; then
   exit 0
fi

GIT_OWNER=$(  echo $TRAVIS_REPO_SLUG | sed "s/\/.*$//" )

if test -z $TRAVIS ; then
    awk '{for(i=1;i<=NF;++i){ if($i=="\\n") {printf("\n"); } else {printf("%s ", $i)} }}' spelling_results
# If not a pull request add a comment on the commit message
elif [ $TRAVIS_PULL_REQUEST=="false" ] ; then
    if [ "$GIT_OWNER" = plumed ] ; then 
        ASPELL_RESULTS=`cat spelling_results`
        curl -i -H "Authorization: token $GIT_TOKEN" \
        -H "Content-Type: application/json" \
        -X POST -d "{\"body\":\"$ASPELL_RESULTS\"}" \
        https://api.github.com/repos/plumed/plumed2/commits/$TRAVIS_COMMIT/comments
    fi
# If it is a pull request comment on the pull request
elif [ "$GIT_OWNER" = plumed ] ; then
    ASPELL_RESULTS=`cat spelling_results`
    curl -i -H "Authorization: token $GIT_TOKEN" \
    -H "Content-Type: application/json" \
    -X POST -d "{\"body\":\"$ASPELL_RESULTS\"}" \
    https://api.github.com/repos/plumed/plumed2/issues/$TRAVIS_PULL_REQUEST/comments
fi

rm -f spelling_results

exit 0
