#!/bin/sh

PIDFILE=/var/run/acix-index.pid
DEFAULT_LOGFILE=/var/log/arc/acix-index.log
prog=twistd

RUN=yes

# sysconfig files
if [ -r /etc/sysconfig/nordugrid ]; then
    . /etc/sysconfig/nordugrid
elif [ -r /etc/default/nordugrid ]; then
    . /etc/default/nordugrid
fi
if [ -r /etc/sysconfig/acix-index ]; then
    . /etc/sysconfig/acix-index
elif [ -r /etc/default/acix-index ]; then
    . /etc/default/acix-index
fi

if [ "$RUN" != "yes" ] ; then
    echo "acix-index service is disabled, please adjust the configuration to your"
    echo "needs and then set RUN to 'yes' in /etc/default/acix-index to enable it."
    return 0
fi

# ARC_CONFIG
if [ "x$ARC_CONFIG" = "x" ] && [ -r /etc/arc.conf ]; then
    ARC_CONFIG=/etc/arc.conf
fi
if [ ! -r "$ARC_CONFIG" ]; then
    echo "ARC configuration not found (usually /etc/arc.conf)"
    exit 1
fi

CONFIG_SECTION=acix\\/indexserver
# read in cacheserver section from arc.conf
# this will put the read values into the environment, e.g., $logfile
eval `sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \
          -e 's/;.*$//' \
          -e 's/[[:space:]]*$//' \
          -e 's/^[[:space:]]*//' \
          -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" \
           < $ARC_CONFIG \
           | sed -n -e "/^\[$CONFIG_SECTION\]/,/^\s*\[/{/^[^;].*\=.*/p;}" `
LOGFILE=${logfile:-$DEFAULT_LOGFILE}
LOGD=`dirname $LOGFILE`
LOGN=`basename $LOGFILE`

if [ ! -d $LOGD ]; then
    mkdir -p $LOGD
fi

APPSTART="
from acix import indexserver;
from twisted.python import log;
from twisted.python.logfile import LogFile;
application = indexserver.createApplication();
log.startLogging(LogFile('$LOGN', '$LOGD', rotateLength=1000000, maxRotatedFiles=25))
"

TACFILE=`mktemp` || exit 1
echo $APPSTART > $TACFILE

exec $prog --pidfile $PIDFILE -y $TACFILE -l $LOGFILE
rm -f $TACFILE
