#!/bin/bash
# Start the specified Axyl Lucene server
# The name of the server should be provided in the
# first command line parameter $1.

# Root Lucene directories..
CONF=/etc/axyl/axyl.conf
test -r $CONF || exit 0
. $CONF
export LUCENE_HOME=${AXYL_HOME}/lucene
export LUCENE_DATA=${AXYL_DATA}/lucene
export LUCENE_LOGS=${AXYL_LOGS}/lucene

# Script filename..
THIS=`basename $0`

# Check we have servers available..
if [ ! -d ${LUCENE_DATA}/servers ]; then
  echo "$THIS: no Lucene servers at ${LUCENE_DATA}/servers"
  exit 1
fi

# A Java runtime is required. Try JAVA_HOME first, and
# if not then try /usr/bin/java..
if [ -z $JAVA_HOME ]; then
  if [ -x /usr/bin/java ]; then
    JAVA_BIN=/usr/bin
  else
    echo "$THIS: java runtime environment not found."
    echo "Install a JRE, and/or define the environment variable"
    echo "JAVA_HOME to point to it."
    exit 1
  fi
else
  JAVA_BIN=${JAVA_HOME}/bin
fi

# Also require Java executable..
JAVA=${JAVA_BIN}/java
if [ ! -x $JAVA ]; then
  echo "$THIS: java executable not found $JAVA"
  exit 1
fi

# And a server name is mandatory too..
if [ "$1" = "" ]; then
  echo "usage: $THIS servername"
  exit 1
else
  SERVER=$1
fi

# Read the globals file for this server. This will define
# the  $LUCENE_LIBS env variable used below..
. ${LUCENE_DATA}/servers/${SERVER}/etc/globals

# Set path..
PATH="${PATH}:${JAVA_BIN}"
export PATH

# Set classpath..
CLASSPATH=
for path in ${LUCENE_LIBS}/*.jar
do
  CLASSPATH="$CLASSPATH:$path"
done
export CLASSPATH

STAMP=`date`
LOGFILE=${LUCENE_LOGS}/${SERVER}/lucene.log
ERRFILE=${LUCENE_LOGS}/${SERVER}/lucene.err
PIDFILE=${LUCENE_DATA}/servers/${SERVER}/${SERVER}.pid
if [ -d ${LUCENE_LOGS}/${SERVER} ]; then
  echo "" >>$LOGFILE
else
  mkdir ${LUCENE_LOGS}/${SERVER}
fi
echo "++++++++++++++++++++++++++++++" >>$LOGFILE
echo "Using classpath: ${CLASSPATH}" >>$LOGFILE
echo "++++++++++++++++++++++++++++++" >>$LOGFILE
echo "Axyl Lucene Server ($SERVER) Startup $STAMP" >>$LOGFILE
echo "Axyl Lucene Server ($SERVER) Startup $STAMP" >>$ERRFILE

$JAVA -Xmx250M -Dnz.net.catalyst.lucene.server.Server.config=${LUCENE_DATA}/servers/${SERVER}/etc/Server.config nz.net.catalyst.lucene.server.Server $@ >>$LOGFILE 2>>$ERRFILE &
PID=$!
echo $PID >$PIDFILE

exit 0