#!/bin/sh

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

RUN=yes

send_systemd_notify() {
    # return if no systemd-notify found
    type systemd-notify >/dev/null 2>&1 || return
    systemd-notify "$@"
}

log_failure_msg() {
    send_systemd_notify --status "Error: $@"
    echo $@
}

# 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/arc-acix-index ]; then
    . /etc/sysconfig/arc-acix-index
elif [ -r /etc/default/arc-acix-index ]; then
    . /etc/default/arc-acix-index
fi

if [ "$RUN" != "yes" ] ; then
    echo "arc-acix-index service is disabled, please adjust the configuration to your"
    echo "needs and then set RUN to 'yes' in /etc/default/arc-acix-index to enable it."
    exit 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

# Check if service is defined in configuration
libexecdir="${ARC_LOCATION:-/usr}/libexec/arc/"
$libexecdir/arcconfig-parser --config $ARC_CONFIG --block acix-index > /dev/null 2>&1
if [ $? -eq 1 ]; then
    log_failure_msg "Block [acix-index] not defined in configuration"
    exit 1
fi

LOGD=`dirname $DEFAULT_LOGFILE`
LOGN=`basename $DEFAULT_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 $DEFAULT_LOGFILE
