#! /bin/bash

# Making sure that plumed executable is available
echo -n "Searching for plumed ..."
if plumed --no-mpi 2>/dev/null 1>/dev/null ; then
  echo " found"
else
  echo " not found"
  echo -n "Sourcing sourceme.sh and searching again ..."
  if source ../sourceme.sh && plumed --no-mpi 2>/dev/null 1>/dev/null ; then
    echo " found"
  else
    echo "ERROR: you should compile plumed first!"
    exit 1
  fi
fi


# initial cleanup
rm -f errors
rm -rf automatic
mkdir automatic

long_version="$(plumed --no-mpi info --long-version)"
git_version="$(plumed --no-mpi info --git-version)"

cat > automatic/version.tmp << EOF
This manual has been compiled from PLUMED version <b> $long_version </b>
(git version: <b> $git_version </b>).
EOF

if test "$TRAVIS" == true ; then
cat >> automatic/version.tmp << EOF
Manual built on Travis CI for branch $TRAVIS_BRANCH.
EOF
fi

if test -d regtests ; then
cat >> automatic/version.tmp << EOF

Regtest results for this version can be found <a href="../regtests/report.html">here</a>.
EOF
fi

for file in ../CHANGES/* ; do
echo "- Changes for \\subpage $(cat $file | grep "@page" | awk '{print $2}')"
done > automatic/changes.tmp

# Check for files that register actions with no documentation
for file in ../src/*/*.cpp
do
  nreg=`grep "PLUMED_REGISTER_ACTION" $file | wc -l | awk '{print $1}'`
  if [ $nreg -gt 0 ] ; then
       ndoc=`grep PLUMEDOC $file | wc -l | awk '{print $1}'`
       if [ $ndoc -eq 0 ] ; then
          echo The following file registered an action but provided no documentation: $file >> errors
       fi
  fi 
done

# Create the list of codes that plumed works with from the set of available patches
for file in ../patches/*.diff
do
   myengine=`echo "$file" | sed -e 's/.diff//' | sed -e 's/..\/patches\///'`
   mytag=`echo "$myengine" | sed -e 's/\./-/g'`
   echo "- $mytag" >> automatic/codesl.list # list only, for Intro
   echo "- \subpage $mytag " >> automatic/codes.list
   echo "/**" >> automatic/$myengine.txt
   echo "\page $mytag $myengine" >> automatic/$myengine.txt
   plumed --no-mpi patch -e $myengine -i -q >> automatic/$myengine.txt
   echo "*/" >> automatic/$myengine.txt 
done

# Generate all the documentation pages from comments
cat ../*/*/*cpp |
awk 'BEGIN{gfile="automatic/GLOSSARY.list"; dfile="automatic/DICTIONARY.list"; }{
  if($1=="//+ENDPLUMEDOC"){
     inside=0;
     print "*/" >output
  }
  if(inside>=2 && NF==0){
     print "</td> </tr>" > lfile
     if(inside==2){ printf "</td> </tr>\n" > gfile; }
     if(inside==3){ printf "</td> </tr>\n" > dfile; }
     inside=1
  }
  if(inside==1 && $1!="/*" && $1!="*/") print $0 >output
  if(inside>=2 && $1!="/*" && $1!="*/" ){
     print $0 > output
     printf "%s", $0 > lfile
     if(inside==2){ printf "%s", $0 > gfile; }
     if(inside==3){ printf "%s", $0 > dfile; }
  }
  if($1=="//+PLUMEDOC"){
    if( $2=="TOPOLOGY" || $2=="COLVAR" || $2=="MCOLVAR" || $2=="DCOLVAR"|| $2=="MCOLVARF" || $2=="MCOLVARB" || $2=="FUNCTION" || $2=="ANALYSIS" || $2=="BIAS" || $2=="GENERIC" || $2=="VATOM" || $2=="TOOLS" ){
      lfile="automatic/"$2".list"
      
      printf "<tr> <td width=%s> \\subpage %s </td> <td>","5%", $3 > lfile
#       printf "<tr> <td width=5%> \\ref %s </td><td> %s </td><td>",$3, $2 > gfile
      printf "<tr> <td width=%s> \\ref %s </td><td> %s </td><td>","5%",$3, $2 > gfile

      if(output!="")close(output);
      output="automatic/"$3".tmp";
      print "/**" > output
      print "\\page "$3" "$3 > output
#      print "\\section "$3 >output
      inside=2;
    } else if ( $2=="INTERNAL" ){
      if(output!="")close(output);

      printf "<tr> <td width=%s> \\subpage %s </td><td> %s </td><td>","5%",$3, $2 > dfile

      output="automatic/"$3".tmp";
      lfile="automatic/"$3".tmp";
      print "/**" > output
      print "\\page "$3" "$3 > output
#      print "\\section "$3 >output
      inside=3;
    }
  }
}'

# Now put all list files in alphabetical order
for file in automatic/*.list ; do

  sort $file > $file-1
  mv $file-1 $file
done


# Generate links to tutorial pages
for file in ./tutorials/*.txt ; do

    link=`grep link: $file | sed -e 's/link://'`
    describe=`grep description: $file | sed -e 's/description://'`

    echo "<tr> <td> $link </td> <td> $describe </td> </tr>" >> automatic/TUTORIALS.list  

done

# Generate links to websites
for file in ./tutorials/*.site; do

   link=`grep link: $file | sed -e 's/link://'`
   describe=`grep description: $file | sed -e 's/description://'`

   echo "<tr> <td> $link </td> <td> $describe </td> </tr>" >> automatic/WEBSITES.list

done

# Find what modules the user has installed
# Find the list of modules
# if [ -d ../mymodules ] ;  then
#  sed -i '' -e 's/type="user" visible="no" url="mymodules.html"/type="user" visible="yes" url="mymodules.html"/' PlumedLayout.xml
echo "<table align=center frame=void width=65%% cellpadding=5%%>" > automatic/modules.list
echo "<tr> <td> <b> Module name </b> </td> <td> <b> Default behavior </b> </td> </tr>" >> automatic/modules.list
for file in `ls ../src/*/module.type | sed -e 's/..\/src\///' | sed -e 's/\/module.type//'`
do
   defoff=0
   dstr=`head ../src/$file/module.type`
   if [ "$dstr" != "always" ] ; then
         echo "<tr> <td> $file </td>" >> automatic/modules.list
         if [ "$dstr" == "default-on" ] ; then
            echo "<td> on </td> </tr>" >> automatic/modules.list
         else 
            echo "<td> off </td> </tr>" >> automatic/modules.list
            defoff=1
         fi
#        # Generate documentation and accreditation on modules page
#        echo "\section $file" >> automatic/mymodules.list
#        echo >> automatic/mymodules.list
#        echo "<table  align=center frame=void width=95%% celpadding=5%%>" >> automatic/mymodules.list
#        echo "<tr> <td width=70%%> </td> </tr> <td>" >> automatic/mymodules.list
#        author=`grep AUTHOR: ../mymodules/available-modules/"$file" | sed -e 's/AUTHOR://'` 
#        echo "<b> author: $author </b>" >> automatic/mymodules.list
#        echo "</td> </tr>" >> automatic/mymodules.list
#        echo "<tr> <td colspan="2">" >> automatic/mymodules.list
#        dline=`grep -n DESCRIPTION: ../mymodules/available-modules/"$file" | sed -n 's/^\([0-9]*\)[:].*/\1/p'` >> automatic/mymodules.list
#        tail -n +$(($dline+1)) ../mymodules/available-modules/"$file" >> automatic/mymodules.list
#        echo "</td> </tr> </table>" >> automatic/mymodules.list
#        echo >> automatic/mymodules.list
#        echo >> automatic/mymodules.list
        
        # Find src files in module and add a link to the module description
        docfiles=$(cat ../src/"$file"/*cpp | grep PLUMEDOC | grep -v END | awk '{print $3;}')
        for docfile in $docfiles ; do
          cat automatic/"$docfile".tmp |
          awk -v o=$defoff '{ print }
          /\\page '$docfile'/{
            if( o==0 ){
                print "<table  align=center frame=void width=95%% celpadding=5%%>"
                print "<tr> <td width=70%%> </td> <td>"
                print "<b> This is part of the '$file' \\link mymodules module \\endlink</b>"
                print "</td> </tr> </table>"
            } else {
                print "<table  align=center frame=void width=95%% celpadding=5%%>"
                print "<tr> <td width=60%%> </td> <td>"
                print "<b> This is part of the '$file' \\link mymodules module \\endlink</b>"
                print "</td> </tr>"
                print "<tr> <td width=60%%> </td> <td>"
                print "<b> It is only available if you add a file called '$file'.on to the plumed2/src directory prior to compilation. "
                print "Furthermore, this feature is still being developed so take care when using it and report any problems on the mailing list.</b>"
                print "</td> </tr>"
                print "</table>"
            }
          }' > automatic/"$docfile"1.tmp
          mv automatic/"$docfile"1.tmp automatic/"$docfile".tmp
        done
   fi 
done
echo "</table>" >> automatic/modules.list
# fi

# Generate all the documentation from keywords
for file in automatic/*.tmp
do
  flag=${file#automatic/}
  flag=${flag/.tmp}
  if grep -q '//+PLUMEDOC INTERNAL' $file 1>/dev/null 2>/dev/null ; then
       cp $file automatic/$flag.txt
  else
     if ! plumed --no-mpi manual --action=$flag > automatic/$flag.man 2> /dev/null ; then 
        echo Full manual for action $flag will not be generated as you are building the manual from a code where this action was not compiled >> errors
     elif ! grep -q "\par Examples" $file 1>/dev/null 2>/dev/null
     then
       echo There are no examples inside documentation for action: $flag >> errors
     fi
       { 
        awk '/\\par Examples/{xx=1}{if(xx==0) printf("%s\n",$0)}' automatic/$flag.tmp
        cat automatic/$flag.man
        awk '/\\par Examples/{xx=1}{if(xx==1) printf("%s\n",$0)}' automatic/$flag.tmp
       } > automatic/$flag.txt
   fi
done

sed -ie 's/<b> --/<b> \\c \\-\\-/g' automatic/*.txt
rm automatic/*.txte

for file in COLVAR MCOLVAR DCOLVAR MCOLVARF MCOLVARB ANALYSIS BIAS GLOSSARY \
            DICTIONARY TUTORIALS WEBSITES FUNCTION TOPOLOGY VATOM \
            TOOLS
do
  mv automatic/$file.list automatic/$file.1.list
  {
    echo "<table align=center frame=void width=95%% cellpadding=5%%>"
    cat automatic/$file.1.list
    echo "</table>"
  } > automatic/$file.list
  rm automatic/$file.1.list
done

# Make all double hyphens appear as double hypens
sed -ie 's/<b> --/<b> \\c \\-\\-/g' automatic/*.txt
rm automatic/*.txte

rm -f *PP.txt
for f in *.txt
do

file=${f%.txt}

# first replace with the content of the files
# then grep out the special strings

cat $file.txt |
  sed "
    /^ *@COLVAR@ *$/r     automatic/COLVAR.list
    /^ *@MCOLVAR@ *$/r    automatic/MCOLVAR.list
    /^ *@DCOLVAR@ *$/r    automatic/DCOLVAR.list
    /^ *@MCOLVARF@ *$/r   automatic/MCOLVARF.list
    /^ *@MCOLVARB@ *$/r   automatic/MCOLVARB.list
    /^ *@ANALYSIS@ *$/r   automatic/ANALYSIS.list
    /^ *@BIAS@ *$/r       automatic/BIAS.list
    /^ *@GLOSSARY@ *$/r   automatic/GLOSSARY.list
    /^ *@DICTIONARY@ *$/r automatic/DICTIONARY.list
    /^ *@TUTORIALS@ *$/r  automatic/TUTORIALS.list
    /^ *@WEBSITES@ *$/r   automatic/WEBSITES.list
    /^ *@FUNCTION@ *$/r   automatic/FUNCTION.list
    /^ *@TOPOLOGY@ *$/r   automatic/TOPOLOGY.list
    /^ *@VATOM@ *$/r      automatic/VATOM.list
    /^ *@TOOLS@ *$/r      automatic/TOOLS.list
    /^ *@MODULES@ *$/r    automatic/modules.list
    /^ *@CODES@ *$/r      automatic/codes.list
    /^ *@CODESL@ *$/r     automatic/codesl.list
    /^ *@VERSION@ *$/r    automatic/version.tmp
    /^ *@CHANGES@ *$/r    automatic/changes.tmp
" | grep -Ev '^ *@[A-Z]*@ *$' > ${file}PP.txt
done
