#!/bin/bash

# Description:
#   This script is designed to add some text to a text file based 
#   apon some values entered in an HTML form. It can be used in conjuction
#   with the script 'plaintext2html-forum.sh' or with the script
#   linkdoc2html-forum. These scripts create the
#   necessary HTML forms and links which will point to this cgi-script
#   
# 
# Notes:
#   The web server must have 'write' permission to the file inorder
#   for this script to achieve anything. If the web-server does not
#   have 'write' permission the script does not complain but the 
#   target file is not updated.
#
#   The version of this script on Debian Linux used the 'fromdos' program,
#   but this is not really a standard unix program (unlike say 'unix2dos')
#   On Debian, 'fromdos' is aliased to 'dos2unix' in any case, so the 
#   'dos2unix' invocation should probably be used for porability.
#   However some HTML textareas, notable Netscape, return strings with neither
#   unix nor dos line endings, but just \r characters. For this we will just
#   use a simple sed conversion.
#
#   This script should include a 'Contribution Heading' parameter, so that 
#   different section headings could be used for the 'comments' section. In other
#   words, in some cases, the document maintainer might want to call the 
#   comment section 'contributions' but in other cases might want to call it
#   'visitor comments' and so on.
# Ideas:
#   make the date a better format, check to see if the file
#   is writable, etc. 
# Dependencies:
#   plaintext2html-forum.sh
#   procgi
#      This is a c program which extracts submitted HTML form values from the
#      posted or 'getted' data sent by the web-visitors browser. This program
#      was found somewhere on the Internet.
# See Also:
#   plaintext2html.sh,
#     Converts a plain text style document into HTML with links and a table of contents
#   plaintext2pdf.sh, 
#     Converts the same type of document into PDF using the 'htmldoc' program
#   plaintext2html-forum.sh
#     Converts a document as above but allows the web-visitor to make contributions
#     via a CGI script called 'add-comment'
#   linkdoc2html.sh
#     Converts a text document which consists of a list of URLs and descriptions into
#     a hyperlinked HTML document
#   diary2html.sh
#     Converts a 'diary style' plain text document into HTML. A diary is just a
#     series of dates and description for those dates
#   linkdoc2html-index.sh, 
#   linkdoc2html-forum.sh
#     Similar to the 'plaintext2html-forum.sh' script but operates on 'linkdocs' as
#     described above.
#   add-comment
#     A CGI script which adds a user supplied comment to a text file and regenerates an
#     HTML file using one of the '2html' scripts described here. The script uses a
#     utility called 'procgi' or 'proccgi' which extracts submitted HTML form values.
# Author:
#    mjb
# Bugs:
#    This script will probably currently fail for strangely named text files. In particular
#    text files which follow the HTML internationalizing naming convention (for use with
#    the 'language negotiation' feature, or 'content negotiation' feature of web-servers
#    and web-browsers) such as 'index.html.en'. This script will probably mangle the
#    name of the generated HTML file.

# The line below parses the querystring or posted environment 
# variables. It uses a program which was found at.
#   http://www.fpx.de/fp/Software/ProcCGIsh.html
# 
eval "`./procgi $*`"

  echo "Content-type: text/html"
  echo ""
  # This second empty echo line IS necessary. A 'server error' will
  # be generated by the web-server if it is not present.

  # echo "A script to add something to a text file"
  sFileName=$FORM_filename
  sComment=$FORM_comment
  sUserName=$FORM_username
  sSourceDocumentType=$FORM_documenttype
  sDebug=$FORM_debug 

  if [ "$sDebug" != "" ]
  then
    echo "
      <pre>
        The variables received by this cgi script were
	sFileName=$sFileName
	sComment=$sComment
	sUserName=$sUserName
	sDebug=$sDebug
      </pre>
         "
  fi
  
  if [ "$sFileName" = "" ] 
  then
      echo "<html>"
      echo "
       <strong><center>
	No file name was specified for the script $0. 
	This is an error. For more information please contact matthew@ella-associates.org  
	The document has not been altered.
       </center></strong>"
      echo "<hr>"
      echo "</html>"
    exit 1;   
  fi

  sHtmlFileName=$(echo $sFileName | sed "s/\.[^\.]*$//gi")".html"

  #-- Check that the directory is writable. If not the text file will be 'truncated'
  #-- by this script and will only contain the comment just added and nothing else.
  #-- This is a very bad outcome and must be avoided at all costs.
  if [ -w $(dirname $sFileName) ]
  then 
    :
  else
    sScriptResultMessage="<strong><center> \
      The directory in which the source file resides is not 'writable' by. \
      the Web Server. You will have to ask the system administrator to make this \
      directory writable in order for this comment script to work \
      The document has not been altered.  <\/center><\/strong><hr>"
     
    cat $sHtmlFileName | sed "s/<body>/<body>$sScriptResultMessage/g"
    exit 1;  
  fi
  
  #-- Check that the file is writable.
  if [ -w $sFileName ]
  then 
    :
  else
    sScriptResultMessage="<strong><center> \
      The source file is not 'writable' by the Web Server. \
      You will have to ask the system administrator to make this \
      file writable in order for this comment script to work \
      The document has not been altered.  <\/center><\/strong><hr>"
     
    cat $sHtmlFileName | sed "s/<body>/<body>$sScriptResultMessage/g"
    exit 1;  
  fi
  
  if [ "$sComment" = "" ] 
  then
    #-- Another 'gotcha': because the string sScriptResultMessage is to be used in
    #-- the sed command, it cannot contain / characters. This may be obvious to some
    #-- Another gotcha: the following sed snippet -e "s#\\#\\\\#g" in my humble opinion
    #-- should actually work but doesn't because the sed engine (gnu I think) seem to
    #-- apply the escaping back-slash to the # character rather than to the other \
    #-- character. Actually this is a quoting problem not a sed problem.
    #-- I cant get this escaping of escape characters to work and frankly I dont care
      #echo "<html>"
      #sSafeFileName=$(echo $sFileName | sed -e 's#/#\\\/#g' -e 's#\\#\\\\#g')
      #sSafeFileName=$(echo $sFileName | sed -e 's#/#\\\/#g' )
      sScriptResultMessage="<strong><center> \
        No comment or other text was specified to be added to the document. \
	The document has not been altered.  <\/center><\/strong><hr>"
       
      cat $sHtmlFileName | sed "s/<body>/<body>$sScriptResultMessage/g"
    exit 1;  
  else
    #-- We need to get rid of the MS Line Ending format, if the 
    #-- text was entered on an MS Windows computer.
    #-- finding the -a switch for fromdos took some time.
    #-- For some reason the 'fromdos' command gets rid of all
    #-- line breaks. It is possible that the 'proccgi' program is 
    #-- doing something unpleasant to the FORM values
    #echo "sComment=$sComment"
    sComment=$(echo $sComment | tr '\r' '\n')
    #sComment=$(echo $sComment | dos2unix | fmt -w80)
    #sComment=$(echo $sComment | sed "s/[\r\n]//g")
    
    echo
  fi

  if [ "$sUserName" = "" ]
  then
    sUserName="[anonymous]"
  fi
 
  #-- Create a 'comments' section heading in the text file if there
  #-- is not one already. If there is already a comments section but
  #-- it is not the last section heading (all capitals line) then this
  #-- won't work as it really should. But thats the nature of shell scripting
  #-- 'good enough is good enough'
  
  if [ "$(cat $sFileName | grep '^[ ]*COMMENTS')" = "" ]
  then
    echo "COMMENTS" >> $sFileName 
  fi
 
  #-- The date string below gives a full text date, with weekday and AM/PM time
  #-- The code below attempts to add the last comment immediately under the 
  #-- comment tag.
  
  cp $sFileName $sFileName.temp
  #-- Preserve the old version of the file, just in case something goes terribly
  #-- wrong. For example, if the web-server does not have permission to write to 
  #-- the directory in the which the text file resides, then the 'cp' command wont 
  #-- work, and nor will the lines below. Back to the drawing board.

  datetag=$(date "+%d%B%Y-%I-%M%p")
  cp $sFileName $sFileName.$datetag

  (sed -n "1,/^[ ]*COMMENTS/p" $sFileName.temp; \
  echo "
  Added by: $sUserName, on $(date '+%A, %d %B %Y, %I:%M %p')

$sComment "; \
  sed "1,/^[ ]*COMMENTS/d" $sFileName.temp; ) > $sFileName 
  rm -f $sFileName.temp
  
  #-- A 'gotcha' is that the full path to the 'plaintext2html-forum.sh' script
  #-- must be included, even though the script is on the bash path. This is,
  #-- I suppose, because the cgi environment does not inherit the environment
  #-- from the bash shell

  #-- Another 'gotcha' is that the 'plaintext2html.sh' script is not working
  #-- properly because it relies on a temporary file, and the web server
  #-- doesn't seem able to create the file. This seems odd because the web
  #-- server is able to create the '.html' transformed file. That is the 
  #-- web-server has sufficient permissions to create a text file from this
  #-- script, but a script which it starts (executes) does not have sufficient
  #-- permissions. I could try giving maximum permission to the filter script
  #-- and see if that helps.

  #-- I have worked around the problem mentioned above by rewriting the 
  #-- filter script (plaintext2html-forum.sh) so that it doesn't write
  #-- to any temporary files

  # echo "sHtmlFileName=$sHtmlFileName"
  if [ "$sSourceDocumentType" = "linkdoc" ]
  then
    /usr/local/bin/linkdoc2html-forum.sh $sFileName > $sHtmlFileName
  elif [ "$sSourceDocumentType" = "plaintext" ]
  then
    /usr/local/bin/plaintext2html-forum.sh $sFileName > $sHtmlFileName
  else
    /usr/local/bin/plaintext2html-forum.sh $sFileName > $sHtmlFileName
  fi
  
  echo "<html>"
  #-- Really, special characters within $username should be 'escaped' so that
  #-- they will not create problems for the 'sed' command. For example if 
  #-- $username contains the character '/' the sed command will probably die
  #-- a sudden painful death.
  #cat $sHtmlFileName
  sResultMessage=" \
   <strong><center> \
     Your comment was added to this document, thankyou $sUserName \
   </center></strong><hr>"
  cat $sHtmlFileName | sed "s/<body>/<body><strong><center>Your comment was added to this document, thankyou $sUserName<\/strong><\/center> /g"