#!/bin/sh
#
# source:
#   /var/cvs/projects/debian/wn/debian/dpkg.src/wn.wncat.in,v
#
# revision:
#   @(#) wn.wncat.in,v 1.4 1999/02/02 03:34:54 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 CGI 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.
#
# bugs:
#   When used with wn the first few non-blank lines of a text file are
#   dropped unless a blank line is first output.  I'm doing this but I
#   don't understand why it is necessary.
#
#   Needs to be factored into functions.


# main:
  set -e


  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

  readonly file_uncompressed="${file%.gz}"

  if [ "${file}" = "${file_uncompressed}" ]
  then
    if [ -r "${file}" ]
    then
      if file -b "${file}" | grep -q "text"
      then
        echo
      fi

      /bin/cat "${file}"
    elif [ -r "${file}.gz" ]
    then
      if file -z -b "${file}.gz" | grep -q "text"
      then
        echo
      fi

      /bin/zcat "${file}.gz"
    else
      echo "${0}: ${file}: No such file"
      exit 1
    fi
  else
    if [ -r "${file}" ]
    then
      if file -z -b "${file}" | grep -q "text"
      then
        echo
      fi

      /bin/zcat "${file}"
    elif [ -r "${file_uncompressed}" ]
    then
      if file -b "${file_uncompressed}" | grep -q "text"
      then
        echo
      fi

      /bin/cat "${file_uncompressed}"
    else
      echo "${0}: ${file}: No such file"
      exit 1
    fi
  fi


  exit 0
