#!/bin/sh

SRV='squid'
CHKCONFIG=/sbin/chkconfig
RUNLEVEL=`/sbin/runlevel | cut -c3`
CATERVA_INDIR="/etc/caterva/$SRV"
CONFDIR=/etc/squid
ALT_CONFDIR="$CONFDIR/alterator"
BACKUP_DIR="$ALT_CONFDIR/backup"
LOGFILE="$ALT_CONFDIR/log"
SERVICE=/sbin/service
PRE_START="sh $CONFDIR/alterator/pre-start.sh"
PRE_STOP="sh $CONFDIR/alterator/pre-stop.sh"

# Checks if a service switched on for the current runlevel?
# args: service
chkconfig_test()
{
    echo `"$CHKCONFIG" --list $1` | grep -q "${RUNLEVEL}:on"
}

# Checks if a service is running.
# args: service
service_test()
{
    "$SERVICE" "$SRV" status | grep -q "is running$"
}

log="$LOGFILE"
date > "$log"
echo >> "$log"

res=0

# Stopping the service
if service_test "$SRV"; then
    echo "\$ $PRE_STOP" >> "$log"
    $PRE_STOP >> "$log" 2>&1
    res=$?
    if [ "$res" -eq 0 ]; then
	echo "\$ $SERVICE $SRV stop" >> "$log"
	"$SERVICE" "$SRV" stop >> "$log" 2>&1
	res=$?
	echo >> "$log"
	[ "$res" -eq 0 ] || echo "Service stop failed" >> "$log"
    else
	echo "Service pre-stop script failed" >> "$log"
    fi
    
fi

# Change service startup status.
if [ "$res" -eq 0 ]; then
    echo "\$ $CHKCONFIG $SRV $1" >> "$log"
    "$CHKCONFIG" "$SRV" "$1" >> "$log" 2>&1
    res=$?
    echo >> "$log"
    [ "$res" -eq 0 ] || echo "Unable to set service startup status" >> "$log"
fi

# Configuration update.
if [ "$res" -eq 0 ] && [ "$1" = "on" ]; then
    echo "\$ verborum-caterva -vr -i \"$CATERVA_INDIR\" -o \"$CONFDIR\" -b \"$BACKUP_DIR\"" >> "$log"
    verborum-caterva -vr -i "$CATERVA_INDIR" -o "$CONFDIR" -b "$BACKUP_DIR" >> "$log" 2>&1
    res=$?
    echo >> "$log"
    [ "$res" -eq 0 ] || echo "Configuration update failed" >> "$log"
fi

# Starting the service.
if [ "$res" -eq 0 ] && [ "$1" = "on" ]; then
    echo "\$ $PRE_START" >> "$log"
    $PRE_START >> "$log" 2>&1
    res=$?
    echo >> "$log"
    if [ "$res" -eq 0 ]; then
	echo "\$ $SERVICE $SRV start" >> "$log"
	"$SERVICE" "$SRV" start >> "$log"
	res=$?
	echo >> "$log"
	[ "$res" -eq 0 ] || echo "Service start failed" >> "$log"
    else
	echo "Service pre-start script failed" >> "$log"
    fi
fi

if [ "$res" -eq 0 ]; then
    echo "Configuration updated successfully" >> "$log"
    date +'%d-%m-%Y %H:%M:%S' >> "$log"
    echo "SUCCESS" >> "$log"
else
    echo "FAIL" >> "$log"
fi

exit $res
