#!/bin/sh
# 愛
# Start s4 - Generate s4.cgi
mydir=`dirname $0`
myname=`basename $0`

script_dir=${SCRIPT_DIR:-scripts}

ADMIN=""
TYPE="form1"
ex=examples

usage() {
  cat<<EOF
$myname		`sed -n 3p $0`
Usage:	$myname [Options]
Options are as follows:
	-h		Show this help
	-a ADM		Set ADMIN email address to ADM
	-f		Force overwriting
	-g		Guestonly mode(No login required)
	-t TYPE		Construction type (defaults to $TYPE)
	-w		Create CGI wrapper

TYPEs are one of directory names in examples except \`common'.
EOF
  exit 0
}
while getopts a:fght:w f; do
  case $f in
    a)	ADMIN=$OPTARG;;
    g)	guest=1;;
    f)	force=1;;
    w)	wrap=1;;
    t)	TYPE=$OPTARG;;
    \?|h)     usage; exit 1;;
  esac
done
shift $(expr $OPTIND - 1)
      
if [ ! -d $ex/$TYPE ]; then
  cat<<EOF 1>&2
Invalid type($TYPE).
Types are one of as follows.
`ls $ex|grep -v common | sed 's/^/	/'`
EOF
  exit 1
fi

if [ -z "$ADMIN" ]; then
  cat<<EOF 1>&2
Administrator's email not specified.
Please feed administrator email with \`-a' option.
EOF
  exit 1
fi

if ! cd $mydir; then
  echo "Script(s4-funcs.sh) not found in \`$mydir'." 1>&2
  exit 1
fi

. ./s4-funcs.sh
if ! checkdomain $ADMIN; then
  cat<<EOF 1>&2
Administrator's email - $ADMIN - is invalid(host not found).
Please specify existing email address.
EOF
  exit 3
fi

if [ -d templ/form ]; then
  if [ -z "$force" ]; then
    echo "templ/ directory already exists.  Remove it, then try again." 1>&2
    exit 4
  fi
  rm -rf templ/*
fi
mkdir templ
if (cd templ && cp -r ../examples/$TYPE/* .); then
  if ./s4-init.sh; then
    cat<<EOF
-------- The s4 System Successfully Installed --------
EOF
    if [ -s scripts/s4-$TYPE.case ]; then
      casefile=scripts/s4-$TYPE.case
    else
      casefile=scripts/s4-default.case
    fi
    m4 -P -I scripts -D_SHELL_=`which sh` \
       -D__NOEDIT__="DO NOT EDIT THIS FILE MANUALLY -> scripts/s4-*.case" \
       -D_CASE_=$casefile s4.cgi.m4 > index.cgi && chmod +x index.cgi
    if [ "$wrap" ]; then
      mv -f index.cgi s4.cgi
    fi
    (echo "ADMIN=$ADMIN"
     echo "S4TYPE=$TYPE"
     [ "$guest" ] && echo "guestonlymode=1") >> s4-config.sh
    sq $db "REPLACE INTO user VALUES('$ADMIN');"
    cat > .htaccess <<-EOF
	DirectoryIndex	index.cgi
	AddHandler cgi-script .cgi
	EOF
    if [ -n "$wrap" ]; then
      ${CC:-gcc} -o index.cgi pwrap.c \
	&& chmod u+s index.cgi \
	&& rc=0
    fi
  else
    echo Calling s4-init.sh 'FAILED!!'
  fi
else
  echo Failed
fi 1>&2

exit ${rc:-5}
