#!/bin/sh
# filename: csv2tab
#########################################################
# This script converts a file containing datafields 
# separated by semicolons into a HTML-TABLE-document.
#
######################################################### Data-Directory when program is used as a CGI-script
#
# as a security measure we don't want to allow the user
# to # specify an arbitrary pathname, so DATADIR is the # directory where our data files are (or below).
# DATADIR can be anywhere, as long as it is 
# world-readable or readable by the http-daemon.
#
# === CHANGE THIS TO YOUR DATA-DIRECTORY ===
DATADIR=/data

cgi_argument_setup(){
   # use first arg as our input-file, allow *.csv only
   FILE=$DATADIR/$1.csv

   # use all other args for title
   shift
   TITLE="$@"
}


# here we use a cheap trick:
# 
#   if QUERY_STRING is set, we assume that this program 
#   is running as a CGI-script
#
if [ -z "$QUERY_STRING" ]; then
   # ===&gt; Running as a plain shell-script now &lt;===
   # f.e.: csv2tab inventory.csv Inventory &gt; inventory.html

   if [ -z "$1" ]; then
      echo "usage: $0 filename title"
      exit
   fi

   # we supply our pathname explicitly 
   # With the arguments
   FILE=$1

   # use all other args for title
   shift
   TITLE="$@"
else
   # ===&gt; Running as CGI-Script now &lt;===
   # f.e.: http://localhost/csv2tab?filename+the+title

   # output MIME-Header for the browser
   #
   echo 'Content-type: text/html'
   echo ''
   #

   # the following trick removes suspicious chars and
   # changes encoded blanks to regular blanks
   #
   cgi_argument_setup `echo $QUERY_STRING |tr ';|&+_' '  '`
fi

#
# create HTML-Header
#
echo "&lt;HTML&gt;&lt;HEADER&gt;&lt;TITLE&gt;$TITLE&lt;/TITLE&gt;&lt;/HEADER&gt;&lt;BODY&gt;"


#
# if file does not exist, then create error-message
# otherwise create heading
#
if [ ! -r $FILE ]; then 
   echo "&lt;H1&gt;sorry, data not found: "
   echo "$FILE"&lt;/H1&gt;&lt;/BODY&gt;&lt;/HTML&gt;"
   exit
else 
   echo "&lt;H1&gt;$TITLE&lt;/H1&gt;"
fi


#
# create the table with a solid borderline
#
echo '&lt;TABLE Border&gt;'           # BEGIN-TABLE

# the first line of an EXCEL-CSV-file consists of the 
# column-names separated by semicolons
# --&gt; treat these different

#
# simple substitutions to create the html table-format
#
cat $FILE |
sed '   1   s,;,&lt;/TH&gt;&lt;TH&gt;,g
        1   s,^,&lt;TR&gt;&lt;TH&gt;,
        1   s,$,&lt;/TH&gt;&lt;/TR&gt;,
        2,$ s,;,&lt;/TD&gt;&lt;TD&gt;,g
        2,$ s,^,&lt;TR&gt;&lt;TD&gt;,
        2,$ s,$,&lt;/TD&gt;&lt;/TR&gt;,
'
echo '&lt;/TABLE&gt;'                 # END-OF-TABLE
echo '&lt;/BODY&gt;&lt;/HTML&gt;'           # END-OF-DOCUMENT
exit

