#! /bin/sh

#================================================================
# estgzhtml
# Decompress a gzipped or zipped file of plain text or HTML.
#================================================================


# set variables
LANG=C ; export LANG
LC_ALL=C ; export LC_ALL
progname="estgzhtml"
tmpfile="/tmp/$progname-$$"
nulldev="/dev/null"
extlist='.txt.gz,.asc.gz,.txt.zip,.asc.zip,.html.gz,.htm.gz,.html.zip,.htm.zip'
infile="$1"
outfile="$2"


# show help message
if [ "$1" = "--help" ]
then
  printf 'Decompress a gzipped or zipped file of plain text or HTML.\n'
  printf '\n'
  printf 'Usage:\n'
  printf '  %s [infile] [outfile]\n' "$progname"
  printf '  estindex register -xsuf %s \\\n' "$extlist"
  printf '      text/html %s casket\n' "$progname"
  printf '\n'
  exit 0
fi


# function to remove the temporary file
tmpclean(){
  rm -rf "$tmpfile"
}


# function to create the temporary file for input
output(){
  if [ -z "$outfile" ]
  then
    cat
  else
    cat >> "$outfile"
  fi
}


# set the exit trap
trap tmpclean 1 2 3 13 15


# check the input file existence
if [ -n "$infile" ] && [ ! -f "$infile" ]
then
  printf '%s: %s: no such file\n' "$progname" "$infile"
  exit 1
fi


# create the temporary file
if [ -z "$infile" ]
then
  cat > "$tmpfile"
  infile="$tmpfile"
fi


# output the result
if printf '%s' "$infile" | egrep '\.(html|htm)\.(gz|zip)$' > "$nulldev" ||
  printf '%s' "$ESTORIG" | egrep '\.(html|htm)\.(gz|zip)$' > "$nulldev"
then
  gzip -cd "$infile" |
    output
else
  printf '<html>\n<body>\n<pre>\n' | output
  gzip -cd "$infile" | sed -e 's/&/\&amp;/g' -e 's/</\&lt;/g' -e 's/>/\&gt;/g' |
    output
  printf '</pre>\n</body>\n</html>\n' | output
fi


# clean up the temporary directory
tmpclean


# exit normally
exit 0



# END OF FILE
