#!/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 'poseidon-details2html-forum.sh' or with the script
#   These scripts create the
#   necessary HTML forms and links which will point to this cgi-script
#   
#   This script has been based directly on the 'add-comment' 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
  sDocumentText=$FORM_DocumentText
  #sUserName=$FORM_username
  sSourceDocumentType=$FORM_documenttype
  sDebug=$FORM_debug 

  if [ "$sDebug" != "" ]
  then
    echo "
      <pre>
        The variables received by this cgi script were
	sFileName=$sFileName
	sDocumentText=$sDocumentText
	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 edit script to work \
      The document has not been altered.  </center></strong><hr>"

    sScriptResultMessage="<strong><center> \
      El directorio en que el archivo est\&aacute; situado no puede ser escrito \
      por el servidor Web. Necesitas pedir del administrador del sistema para que \
      pueda arreglar esta situaci\&oacute;n \
      </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> \
      El archivo no puede ser escrito por el servidor Web. \
      Es preciso pedir del administrador del sistema que arregle esta \
      situaci\&oacute;n. El documento no ha sido cambiado <\/strong><hr>"
     
    #sScriptResultMessage="<strong> \
    #  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 document edit script to work \
    #  The document has not been altered.  <\/strong><hr>"
     
    cat $sHtmlFileName | sed "s|<body>|<body>$sScriptResultMessage|g"
    exit 1;  
  fi
  
  #-- Check that the html file is writable.
  if [ -w $sHtmlFileName ]
  then 
    :
  else
    sScriptResultMessage="<strong> \
      El archivo HTML no puede ser escrito por el servidor Web. \
      Es preciso pedir del administrador del sistema que arregla esta \
      situaci\&oacute;n. El documento no ha sido cambiado</strong><hr>"

      #The HTML 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 document edit script to work \
      #The document has not been altered. </strong><hr>"
     
      cat $sHtmlFileName | sed "s|<body>|<body>$sScriptResultMessage|g"
    exit 1;  
  fi
  
  if [ "$sDocumentText" = "" ] 
  then
      sScriptResultMessage="<strong> \
        El texto del documento ha sido borrado. Tal vez, no es un buen idea. El documento \
	no ha sido cambiado </strong><hr>"
	
        #The text of the document has been obliterated. This is probably not a good idea \
	#The document has not been altered.  </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.
    #echo "sDocumentText=$sDocumentText"
    #sDocumentText=$(echo $sDocumentText | tr '\r' '\n')
    #-- 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.previous
    #-- 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

    # We need to convert from iso whatever into UTF-8 
    # echo "last modified on $(date '+%A, %d %B %Y, %I:%M %p')"
      #-- We are going to need an actual text file for the transformation script, so...
    echo $sDocumentText | tr '\r' '\n' | \
      iconv --from-code=ISO-8859-1 --to-code=UTF-8 > $sFileName
    
    echo
  fi

  if [ "$sUserName" = "" ]
  then
    sUserName="[anonymous]"
  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.previous
  #-- 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

  # echo "last modified on $(date '+%A, %d %B %Y, %I:%M %p')"

  # The web server needs write permissions on the directory. 
  # echo "sHtmlFileName=$sHtmlFileName"
  if [ "$sSourceDocumentType" = "poseidon" ]
  then
    #-- Since many of the pages on the 'Poseidon' site a multi-lingual there is
    #-- not any point having links to Googles automatic translation
    /usr/local/bin/poseidontext2html-forum.sh $sFileName notran > $sHtmlFileName
  elif [ "$sSourceDocumentType" = "plaintext" ]
  then
    /usr/local/bin/plaintext2html-forum.sh $sFileName > $sHtmlFileName
  else
    /usr/local/bin/plaintext2html-forum.sh $sFileName > $sHtmlFileName
  fi
  
  #-- Watch out for special 'sed' characters in the sScriptResultMessage variable 
  #-- The translation link wont work from with the cgi directory

  #cat $sHtmlFileName
  sScriptResultMessage=" \
   <strong> El documento ha sido puesto al d\&iacute;a. Gracias </strong><br><br> \
   <em>  Your changes have been included in this document, thankyou </em><hr>"

  sed "s|<body>|<body>$sScriptResultMessage|g" $sHtmlFileName 
  #sed "s|Vea este pagina en (aproximado):||g" | \ 
  #sed "s|>Ingl&eacute\;s<|><|g"