#!/usr/local/bin/zsh

# Setup section:
HTTP_ROOT=/usr/local/etc/httpd/htdocs
INDEX=index.html
USER_HTML=public_html
ZCAT=/usr/bin/zcat
# End of Setup section

function error () {
  << EOF
<head><title>$1</title></head>
<body><h1>$1</h1>
$2
</body>
EOF
}

function expand_URL () {
  if [[ ${1#/} != $1 ]]; then
    root=$HTTP_ROOT/$1
    name=$root
  elif [[ ${1#\\\~} != $1 ]]; then
    if [[ ${1%%/}/ = $1 ]]; then
      user=${${1#\\}%%/}
      root=${user}/$USER_HTML
      name=$root/$INDEX
    elif [[ ${1%%/[^/]*} = $1 ]]; then
      user=${1#\\}
      root=${user}/$USER_HTML
      name=$root/$INDEX
    else
      user=${${1%%/[^/]*}#\\}
      root=${user}/$USER_HTML${${1#\\}#$user}
      name=/${1#[^/]*/}
      if [[ -d ${~root} ]]; then
	name=$root/$INDEX
      else
	if [[ -f ${~root}.gz ]]; then
	  name=$root
	else
	  if [[ -f ${~root}.html.gz ]]; then
	    name=$root.html
	  elif [[ -f ${~root}.html ]]; then
	    name=$root.html
	  else
	    name=$root
	  fi
	fi
      fi
    fi
    root=$name
    name=${~name}
  else
    error "Invalid Request" "<pre>Syntax:\012  zcat ~username/[path/]filename[.html]\012or\012  zcat /[path/]filename[.html]</pre>"
    exit
  fi
}

echo Content-type: text/html
echo

expand_URL $1

if [[ ${name#*../} != $name ]]; then
  error "Invalid Request" "<pre>You may not request filenames containing \"..\".</pre>"
  exit
fi

if [[ -f $name.gz ]]; then
  if [[ -r $name.gz ]]; then
    $ZCAT $name
  else
    error "Permission Denied" "You don't have permission to read $root."
  fi
elif [[ -f $name ]]; then
  if [[ -r $name ]]; then
    cat $name
  else
    error "Permission Denied" "You don't have permission to read $root."
  fi
else
  error "File not Found" "The file $root does not exist."
fi

