#!/bin/sh

SRV='squid'
CONFDIR=/etc/squid
SRV_CONF="$CONFDIR/squid.conf"
ALT_CONFDIR="$CONFDIR/alterator"
BACKUP_DIR="$ALT_CONFDIR/backup"
LOGFILE="$ALT_CONFDIR/log"
SERVICE=/sbin/service
HELPER=/usr/lib/alterator/backend3/helper/squid_commit_helper

alterator_api_version=1
. alterator-sh-functions
po_domain="alterator-squid"

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

# Checks if debug mode is on.
test_debug()
{
    [ -n "${ALTERATOR_DEBUG:-}" ]
}

# Checks if helper is running.
# args: helper-name
test_helper()
{
    local hpid=`pidof -sx "$1"`
    [ -n "$hpid" ]
}

on_message()
{
    set_locale
    case "$in_action" in
	read)
	    if test_helper "$HELPER"; then
		write_string_param 'update' "`_ 'in progress...'`"
		write_bool_param 'helper' 'on'
	    else
		write_bool_param 'helper' 'off'
		if [ -f "$LOGFILE" ]; then
		    if [ -f "$SRV_CONF" ] && [ "$SRV_CONF" -nt "$LOGFILE" ]; then
			write_string_param 'update' "`_ 'manually updated'`"
		    else
			local ustatus=`tail -1 "$LOGFILE"`
			local umsg=`tail -2 "$LOGFILE" | head -1`
			if [ -n "$ustatus" ]; then
			    case "$ustatus" in
				SUCCESS)
				    write_string_param 'update' "$umsg"
				    ;;
				FAIL)
				    umsg=`_ "$umsg"`
				    write_string_param 'update' "$umsg"
				    ;;
				*)
				    write_string_param 'update' "`_ 'unknown'`"
				    ;;
			    esac
			else
			    write_string_param 'update' "`_ 'unknown'`"
			fi
		    fi
		else
		    write_string_param 'update' "`_ 'never'`"
		fi
	    fi

	    if service_test "$SRV"; then
		write_bool_param 'status' 'on'
	    else
		write_bool_param 'status' 'off'
	    fi

	    write_string_param 'backup_dir' "$BACKUP_DIR"
	    ;;
	write)
	    if [ -n "$in_commit" ] && test_bool "$in_commit"; then
		if test_bool "$in_status"; then
		    "$HELPER" 'on' &
		else
		    "$HELPER" 'off' &
		fi
		sleep 1
	    fi
	    ;;
    esac
}

message_loop
