#!/bin/sh
# $Id: run-main 3010 2007-12-10 13:36:55Z topia $
# copyright (C) 2004 Topia <topia@clovery.jp>. all rights reserved.

if [ -z "${THISDIR}" ]; then
  echo "$0 couldn't use directly. please use ./run." 1>&2
  exit 2;
fi
[ "0${DEBUG}" -ge 1 ] && echo "${THISDIR}/run-main: start"

PERL=${PERL:-/usr/bin/perl}
PERLARG=${PERLARG:--w}
TIARRA=${TIARRA:-${TOPDIR}/tiarra}
CONF=${CONF:-tiarra.conf}
REDIR_STDOUT=${REDIR_STDOUT:->errlog.stdout}
REDIR_STDERR=${REDIR_STDERR:->errlog.stderr}
REDIR_STDIN=${REDIR_STDIN:-&-}
DAEMON_MODE=${DAEMON_MODE:-yes}

eval "${LAZY_EXECUTE}"

cmd_line='${PERL} ${PERLARG}'
cmd_line="${cmd_line} "'${TIARRA}'
cmd_line="${cmd_line} "'--config="${CONF}"'
cmd_line="${cmd_line} ${TIARRAARG}"
cmd_line="${cmd_line} "'"$@"'
[ "X${REDIR_STDOUT}" = "X-" ] || cmd_line="${cmd_line} >${REDIR_STDOUT}"
[ "X${REDIR_STDERR}" = "X-" ] || cmd_line="${cmd_line} 2>${REDIR_STDERR}"
[ "X${REDIR_STDIN}" = "X-" ] || cmd_line="${cmd_line} <${REDIR_STDIN}"

if [ "X${DAEMON_MODE}" = "Xyes" ]; then
  cmd_line="${cmd_line} &"
else
  cmd_line="exec ${cmd_line}"
fi


if [ \! -z "${DEBUG}" ]; then
  echo "    configuration"
  echo "workdir   : ${WORKDIR}"
  echo "perl      : ${PERL}"
  echo "perl arg  : ${PERLARG}"
  echo "tiarra    : ${TIARRA}"
  echo "config    : ${CONF}"
  echo "tiarra arg: ${TIARRAARG}"
  echo "extra     : $@"
  echo "stdout    : ${REDIR_STDOUT}"
  echo "stderr    : ${REDIR_STDERR}"
  echo "stdin     : ${REDIR_STDIN}"
  echo "daemon    : ${DAEMON_MODE}"
  echo "lazy exec : "
  echo "${LAZY_EXECUTE}" | while read line ; do echo "    $line" ; done
  echo "cmdline   :"
  echo "    ${cmd_line}"
else
  cd "${WORKDIR}"
  eval "${cmd_line}"
fi
