#!/opt/gnu/bin/bash

awk="/opt/gnu/bin/gawk"
tsdb_home="/export/apache/virtual/cl-www/docs/tsnlp/tsdb"
tsdb="${tsdb_home}/bin/tsdb -ofs=@"
queries="${tsdb_home}/log/queries"
errors="${tsdb_home}/log/errors"
date="$(/bin/date)"
remote="${REMOTE_HOST}"

echo Content-type: text/html
echo

expand() {
  echo "$*" | \
  ${awk} 'BEGIN { RS="&"; FS="=" }
          /^[a-zA-Z0-9_]*=/ { printf("%s=\047%s\047\n", $1, $2); }
          /copy\.[xy]=/ { printf("copy=\047%s\047\n", $2); }
          /submit\.[xy]=/ { printf("submit=\047%s\047\n", $2); }'
} # expand()
 
normalize() {
  echo "$*"| /bin/sed -e 's/++*/ /g' \
                      -e 's/%21/!/g' \
                      -e 's/%22/"/g' \
                      -e 's/%24/$/g' \
                      -e 's/%26/\&/g' -e 's/&&/\&/g' \
                      -e 's/%27/"/g' \
                      -e 's/%28/(/g' \
                      -e 's/%29/)/g' \
                      -e 's/%2B/\+/g' \
                      -e 's/%3A/:/g' \
                      -e 's/%3C/</g' \
                      -e 's/%3D/=/g' -e 's/==/=/g' \
                      -e 's/%3E/>/g' \
                      -e 's/%3F/?/g' \
                      -e 's/%5B/[/g' \
                      -e 's/%5D/]/g' \
                      -e 's/%5E/^/g' \
                      -e 's/%60/"/g' \
                      -e 's/%7C/|/g' -e 's/||/|/g' \
                      -e 's/%7E/~/g' -e 's/match(\(..*\),\(..*\))/\1 ~ \2/g' \
                      -e 's/ *\. *$//' -e 's/ *$//'
} # normalize

quote() {
  echo "$*" | \
#
# the removal of double quotes is required to work around a bug in Mosaic
# preventing the proper interpretation of `&quot;C&quot;' (31-jul-95 -- oe)
#
  ${awk} '{ for(i = 1; i <= NF; i++) {
              if($i ~ /^".+"$/) {
                printf("\140%s\047 ", substr($i, 2, length($i) - 2));
              } # if
              else {
                printf("%s ", $i);
              } # else
            } # for
            printf("\n");
          }' | \
  /bin/sed -e 's/&/\&amp;/g' \
           -e 's/>/\&gt;/g' \
           -e 's/</\&lt;/g' \
           -e 's/"/\&quot;/g' 
} # quote()

title() {

cat << EOF

  <title>Interactive tsdb(1) Query Interface</title>

  <h1>
  Interactive tsdb(1) Query Interface</h1>
  <hr>

EOF

} # title()

body() {

cat << EOF

  <p>
  From this page you are given on-line (though read-only) access to the
  TSNLP test suite database (tsdb(1)); in order to successfully
  retrieve data from tsdb(1) you will have to know and
  understand at least some of the database internals:
  <ul>
  <li> some <a href="/tsnlp/tsdb/figures.html">background information</a>
       (basic entity types and size of the database);
  <li> the <a href="/tsnlp/tsdb/schema.html">database schema</a> (as an 
       abstract entity-relationship diagram);
  <li> the <a href="/tsnlp/tsdb/tsdb.cgi?-relations">relations</a>
       involved (together with the names and types of attributes);
  <li> the <a href="/tsnlp/tsdb/tsql.html"> query language</a>
       interpreted by tsdb(1) (an improper subset of SQL);
  <li> tsdb(1) <a href="/tsnlp/tsdb/tsdb.cgi?-usage">command line synopsis</a>;
  <li> tsdb(1) <a href="/tsnlp/tsdb/tsdb.cgi?-version">
       version and revision</a> information.
  </ul>

  <p>
  Alternatively, take a look at <a href="/tsnlp/tsdb/samples.html"> a
  set of example queries</a> demonstrating several interesting aspects
  of the test data and database.
  <hr>

EOF

} # body()

input() {

  echo "<b>Query to the TSNLP test suite database:</b>"
  echo "<form action=\"/tsnlp/tsdb/tsdb.cgi\">"
  echo "TSNLP test data currently available in"
  if [ "${language}" = "english" ]; then
    echo "<input type="radio" name="language" value="english" checked>"
    echo "<i>English</i><tt> </tt>"
    echo "<input type="radio" name="language" value="french">"
    echo "<i>French</i><tt> </tt>or<tt> </tt>"
    echo "<input type="radio" name="language" value="german">"
    echo "<i>German</i>."
  else \
    if [ "${language}" = "french" ]; then
      echo "<input type="radio" name="language" value="english">"
      echo "<i>English</i><tt> </tt>"
      echo "<input type="radio" name="language" value="french" checked>"
      echo "<i>French</i><tt> </tt>or<tt> </tt>"
      echo "<input type="radio" name="language" value="german">"
      echo "<i>German</i>."
    else \
      echo "<input type="radio" name="language" value="english">"
      echo "<i>English</i><tt> </tt>"
      echo "<input type="radio" name="language" value="french">"
      echo "<i>French</i><tt> </tt>or<tt> </tt>"
      echo "<input type="radio" name="language" value="german" checked>"
      echo "<i>German</i>."
    fi
  fi
  echo "<input type=\"text\" name=\"query\" value=\"${qquery}\" size=\"80\">"
  echo "</form>"

} # input()

options() {
  echo "<hr>"
  echo "<b>[<a href=\"/tsnlp/tsdb/tsdb.cgi?language=${language}&modify=${oquery}\">modify query</a>]</b>"
  echo "<b>[<a href=\"/tsnlp/tsdb/tsdb.cgi?language=${language}&\">new query</a>]</b>"
  echo "<b>[<a href="/tsnlp/tsdb/samples.html">sample queries</a>]</b>"
  echo "<b>[<a href="/tsnlp/tsdb/statistics.cgi">query statistics</a>]</b>"
  echo "<b>[<a href="/tsnlp/">TSNLP home</a>]</b>"
  echo "<hr><i>last modified: 21-aug-95 ("
  echo "<a href=\"http://cl-www.dfki.uni-sb.de/~oe\">"
  echo "oe@cl.dfki.uni-sb.de</a>)</i>"
} # options()


# -----------------------------------------------------------------------------
# body of `tsdb.cgi'
# -----------------------------------------------------------------------------

#echo "${QUERY_STRING}" >> /tmp/xxx

if [ $# -gt 0 ]; then
  for i in $*; do
    case $i in
      -version)
        version=$(eval ${tsdb} -version 2>&1)
        echo "<title>Current tsdb(1) Version Information</title>"
        echo "<h1>Current tsdb(1) Version Information</h1><p><hr><p>"
        echo "<blockquote>$version</blockquote>"
        options
        exit 0
        ;;
      -relations)
        relations=$(${tsdb} -home=${language:-german} -query="info relations")
        echo "<title>Current tsdb(1) Relations</title>"
        echo "<h1>Current tsdb(1) Relations</h1><p><hr><p>"
        echo "<blockquote><pre>$relations</pre></blockquote>"
        options
        exit 0
        ;;
      -usage)
        usage=$(${tsdb} -usage 2>&1 | sed 's/$/<br><dd>/g')
        echo "<title>tsdb(1) Command Line Synopsis</title>"
        echo "<h1>tsdb(1) Command Line Synopsis</h1><p><hr><p>"
        echo "<dl><dt>$usage</dl>"
        options
        exit 0
        ;;
    esac
  done
fi

title
body

if [ "${QUERY_STRING}" ]; then
  eval "$(expand "$QUERY_STRING")";
  if [ "${query}" ]; then
    oquery="${query}"
    query="$(normalize "${query}")"
    qquery="$(quote "${query}")"
  fi
fi

if [ "${modify}" ]; then
  oquery="${modify}"
  query="$(normalize "${modify}")"
  qquery="$(quote "${query}")"
  unset query
fi

if [ "${selecta}" ]; then
  oquery="$(echo ${selecta} | /bin/sed 's/%28[0-9]*%29//')"
  query="$(normalize "${oquery}")"
  qquery="$(quote "${query}")"
  if [ "${copy}" ]; then
    unset query
  fi
else \
  if [ "${selectb}" ]; then
    oquery="${selectb}"
    query="$(normalize "${oquery}")"
    qquery="$(quote "${query}")"
    if [ "${copy}" ]; then
      unset query
    fi
  fi
fi

input

if [ "${query}" ]; then
  command="${tsdb} -home=${language:-german} -pager="null""
  command="${command} -debug=/tmp/.tsdb.debug.$$ -query='${query}'"
#echo "'$command'" >> /tmp/xxx
  ( 
    eval "$command"
  ) > /tmp/.tsdb.$$ 2> /tmp/.tsdb.error.$$
  error=$?
  if [ -s /tmp/.tsdb.error.$$ ]; then
    echo "[${remote}] ${date}: ${query}" >> "$errors"
    echo "<hr>"
    echo "<b>Error:</b><p><blockquote><pre>"
    cat /tmp/.tsdb.error.$$
    echo "</pre></blockquote>"
  else \
    if [ -s /tmp/.tsdb.$$ ]; then
    echo "[${remote}] ${date}: ${query}" >> "$queries"
    echo "<hr>"
    echo "<b>Result of this database query "
    echo "($(wc -l /tmp/.tsdb.$$ | awk '{print $1}') matching records):"
    echo "</b><p><blockquote><pre>"
    sed 's/@/ × /g' /tmp/.tsdb.$$
    echo "</pre></blockquote>"
    else \
      echo "<hr>"
      echo "<b>No match for this tsdb(1) query.</b>"
      if [ $error -ne 0 ]; then
        ( echo "query: \`${query}'"
          if [ -s /tmp/.tsdb.$$ ]; then
            echo; echo; echo "result file:"; echo
            cat /tmp/.tsdb.$$ 
          fi
          if [ -s /tmp/.tsdb.error.$$ ]; then
            echo; echo; echo "error file:"; echo
            cat /tmp/.tsdb.error.$$ 
          fi
          if [ -s /tmp/.tsdb.debug.$$ ]; then
            echo; echo; echo "debug file:"; echo
            cat /tmp/.tsdb.debug.$$
          fi
        ) | /usr/ucb/mail \
              -s "$language: failed tsdb query (from \`${remote}')" \
              oe@cl fettig@cl
      fi
    fi
  fi
  /bin/rm -f /tmp/.tsdb.$$ /tmp/.tsdb.error.$$ /tmp/.tsdb.debug.$$
fi

options

