#!/bin/sh
#
# source:
#   $Source: /var/cvs/projects/debian/wn/debian/dpkg.src/wn.wncat.in,v $
#
# revision:
#   @(#) $Id: wn.wncat.in,v 1.3 1998/11/20 18:14:03 jplejacq Exp $
#
# copyright:
#   Copyright (C) 1999 Jean Pierre LeJacq <jplejacq@quoininc.com>
#
#   Distributed under the GNU GENERAL PUBLIC LICENSE.
#
# synopsis:
#   wncat <directory> [<file>]
#
# description:
#   Prints the <file> or ${WN_KEY} to standard output.
#
#   This is a program intended to be used by the wn HTTP server.  It
#   looks for a second argument or if not available it looks for a
#   file name in the environment variable WN_KEY and concatenates that
#   to the directory <directory>.  It will then search for either a
#   compressed or uncompressed version and print it to standard
#   output.  The compressed version is assumed to have the suffix
#   ".gz" and can be uncompressed with zcat.
#
#   This program can be run either as a CGI/1.1 program or a wn
#   File-Module.  A File-Module will have the entire HTTP header
#   handled by the wn server.  A CGI program normally must handle the
#   header itself.  This program makes the assumption that the
#   appropriate wn index directives, such as Content-Type, are used so
#   all that is required is a header separator.  This program decides
#   how it is being run by checking if the environment variable WN_KEY
#   is defined.  If so, it assumes it is a File-Module.


# main:
  set -e


  # parse input:
    if [ 1 -gt ${#}  -o  2 -lt ${#} ]
    then
      echo "${0}: Usage: ${0} <directory> [<file>]"
      exit 1
    fi

    readonly dir="${1}"

    if [ 2 -eq ${#} ]
    then
      readonly file="${dir}/${2}"
    else
      readonly file="${dir}/${WN_KEY}"
    fi



  # output header seperator if run as CGI program:
    if [ -z "${WN_KEY}" ]
    then
      echo
    fi



  if [ "gz" = "${file##*.}" ]
  then
    #
    # Requested gzip compressed file.
    #
    # WN will send the HTTP/1.1 header "Content-encoding: x-gzip" to the
    # client.  We therefore have to send the file compressed.
    #

    if [ -r "${file}" ]
    then
      cat "${file}"
    elif [ -r "${file%.gz}" ]
    then
      cat "${file%.gz}" | gzip -
    else
      echo "${0}: ${file}: No such file (compressed or uncompressed)"
      exit 1
    fi
  else
    #
    # Requested uncompressed file.
    #
    # WN will send the HTTP/1.1 header "Content-type: ..." to the
    # client with the "..." replaced with MIME type of the requested
    # file.  We therefore have to send the file uncompressed.
    #

    if [ -r "${file}" ]
    then
      cat "${file}"
    elif [ -r "${file}.gz" ]
    then
      zcat "${file}.gz"
    else
      echo "${0}: ${file}: No such file (compressed or uncompressed)"
      exit 1
    fi
  fi


  exit 0
