#!/bin/bash
##
## Mailman Hack: Archive search by Hyper Estraier (estseek.cgi)
## Copyright (c) 2008 SATOH Fumiyasu @ OSS Technology Co., Ltd.
##                    <http://www.osstech.co.jp/>
##
## License: GNU General Public License version 2 or later
## Date: 2008-08-15, since 2008-07-25
##

set -u

debug_f="${MM_ESTRAIER_DEBUG:-}"

archive_dir="${MM_VARDIR:-/opt/osstech/var/lib/mailman}/archives"
private_dir="$archive_dir/private"
public_dir="$archive_dir/public"

pdie()
{
  echo "$0: ERROR: $*" 1>&2
  exit 1
}

## ======================================================================

## Remove trailing '/'
path_info_tmp="${PATH_INFO#/}"
path_info="${path_info_tmp#*/}"
list_name=$(echo "${path_info_tmp%%/*}" |tr '[A-Z]' '[a-z]')
private_cgi="`dirname "$SCRIPT_FILENAME"`/private"

if [ -n "$debug_f" ]; then
  echo "content-type: text/plain"
  echo
  echo "path_info: $path_info"
  echo "list_name: $list_name"
  echo "private_cgi: $private_cgi"
  env |sed 's/^/env: /'
fi

## ======================================================================

if [ -d "$public_dir/$list_name" ]; then
  if [ -n "$debug_f" ]; then
    echo "result: This is a public list"
  fi
else
  private_out=$(PATH_INFO="/$list_name/" "$private_cgi")
  private_ret="$?"
  if [ "$private_ret" -ne 0 ]; then
    pdie "$private_cgi failed: exit status: $private_ret" 1>&2
  fi

  case "$private_out" in
  *\"username\"*\"password\"*\"submit\"*)
    if [ -n "$debug_f" ]; then
      echo "result: Unauthorized by $private_cgi"
    fi
    echo "$private_out"
    exit 0
    ;;
  esac

  if [ -n "$debug_f" ]; then
    echo "result: Authorized by $private_cgi"
    echo "$private_out" |sed 's/^/private_out: /'
  fi
fi

cd "$private_dir/$list_name/estraier" || pdie "Cannot change working directory"
SCRIPT_NAME="$SCRIPT_NAME/$list_name"
export SCRIPT_NAME
exec ./estseek.cgi
pdie "Cannot execute estseek.cgi"

