#!/usr/bin/env bash

# Automatic start script for crabd, designed to be run from cron.
# For example, to check that the server is running every 10 minutes:
#
#   PATH=/path/to/crab/scripts:/bin:/usr/bin
#   PYTHONPATH=/path/to/crab/lib
#   5-55/10 * * * * crabd-check
#
# It keeps track of the server's PID and restarts it if that process
# is not running.  It also redirects the output from crabd into
# a log file.

# Select directory for PID file.
# Try /var/run otherwise use /tmp.

if [ -w /var/run ]
then
    RUNDIR=/var/run
else
    RUNDIR=/tmp
fi

# Select directory for log file.
# Try /var/log/crab otherwise /var/tmp/crab or /tmp.

if [ -w /var/log/crab ]
then
    LOGDIR=/var/log/crab
elif [[ -w /var/log && ! -e /var/log/crab ]]
then
    LOGDIR=/var/log/crab
    mkdir $LOGDIR
elif [ -w /var/tmp/crab ]
then
    LOGDIR=/var/tmp/crab
elif [[ -w /var/tmp && ! -e /var/tmp/crab ]]
then
    LOGDIR=/var/tmp/crab
    mkdir $LOGDIR
else
    LOGDIR=/tmp
fi

# Set file names.

PIDFILE=$RUNDIR/crabd-$UID.pid
LOGFILEACC=$LOGDIR/crabd-$UID-access.log
LOGFILEERR=$LOGDIR/crabd-$UID-error.log

# Launch crabd using its own PID file mechanism.

crabd --pidfile $PIDFILE --accesslog $LOGFILEACC --errorlog $LOGFILEERR --daemon > /dev/null 2>&1
