#!/bin/bash

cd html

if [ ! -e tutorial-resources ] ; then
  mkdir tutorial-resources
fi
cd ../


for file in ./tutorials/*.txt ; do

   check=`grep additional-files: $file | wc -l`
   if [ $check -gt 1 ] ; then
        echo Input files for tutorials should all be given in a single tarball. $file contains $check files >> errors
   elif [ $check -gt 0 ] ; then
      resources=`grep additional-files: $file | sed -e 's/additional-files: //'`
     for addfile in $resources; do 
        if test -d tutorials/$addfile; then
          cd tutorials
          tar czf ../html/tutorial-resources/$addfile.tar.gz $addfile
          cd -
        else
          cp tutorials/$addfile html/tutorial-resources
        fi
     done
   fi

done

for file in ./tutorials/others/*.txt ; do

   check=`grep additional-files: $file | wc -l`
   if [ $check -gt 1 ] ; then
        echo Input files for tutorials should all be given in a single tarball. $file contains $check files >> errors
   elif [ $check -gt 0 ] ; then
      resources=`grep additional-files: $file | sed -e 's/additional-files: //'`
     for addfile in $resources; do 
        if test -d tutorials/others/$addfile; then
          cd tutorials
          tar czf ../html/tutorial-resources/$addfile.tar.gz others/$addfile
          cd -
        else
          cp tutorials/others/$addfile html/tutorial-resources
        fi
     done
   fi

done

nerrors=`wc -l errors | awk '{print NF}'`
if [ $nerrors -eq 0 ] ; then
  rm errors
else
  echo "************************************************"
  echo "Found the following errors in your documentation"
  echo ""
  cat errors
  echo "************************************************"
fi

# Test for existance of errors in example input files
if [ ! -f example_errors ] ; then
   exit 0
fi

echo "************************************************"
echo "Found errors in examples in documentation"
echo ""
cat example_errors
echo "************************************************"

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

# If not a pull request add a comment on the commit message
if [ $TRAVIS_PULL_REQUEST=="false" ] ; then
    if [ "$GIT_OWNER" = plumed ] ; then
        EXGEN_RESULTS=`cat example_errors`
        curl -i -H "Authorization: token $GIT_TOKEN" \
        -H "Content-Type: application/json" \
        -X POST -d "{\"body\":\"$EXGEN_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
    EXGEN_RESULTS=`cat example_errors`
    curl -i -H "Authorization: token $GIT_TOKEN" \
    -H "Content-Type: application/json" \
    -X POST -d "{\"body\":\"$EXGEN_RESULTS\"}" \
    https://api.github.com/repos/plumed/plumed2/issues/$TRAVIS_PULL_REQUEST/comments
fi

exit 0
