#!/bin/sh
#
#
# chkconfig: - 95 25
# description: Online squidmill database update service

# Source function library.
. /etc/init.d/functions

PIDFILE=/var/run/squidmill.pid
LOCKFILE=/var/lock/subsys/squidmill
SQUIDLOGFILE=
SQUIDLOGUSER=
DBFILE=/var/log/squid/squidmill.db
SQUIDCONF=/etc/squid/squid.conf

# Source networking configuration.
SourceIfNotEmpty /etc/sysconfig/squidmill

start()
{
    if [ -z "$SQUIDLOGFILE" ] || [ -z "$SQUIDLOGUSER" ]; then
        if [ -n "$SQUIDCONF" ] && [ -f "$SQUIDCONF" ]; then
            res="`sed -n -e 's/^[[:space:]]*access_log[[:space:]]\+"\?\(\/.*\)"\?[[:space:]]\+\([^[:space:]]\+\).*$/\1:\2/p' "$SQUIDCONF" | tail -1`"
            if [ -z "$res" ]; then
		res="`sed -n -e 's/^#[[:space:]]*access_log[[:space:]]\+"\?\(\/.*\)"\?[[:space:]]\+\([^[:space:]]\+\).*$/\1:\2/p' "$SQUIDCONF" | tail -1`"
            fi
            if [ -z "$res" ]; then
                printf "Squidmill: read access.log location from $SQUIDCONF"
                failure "access_log not found"
                echo
                exit 1
            fi
            if [ -z "$SQUIDLOGFILE" ]; then
              SQUIDLOGFILE="${res%%:*}"
            fi
            if [ -z "$SQUIDLOGUSER" ]; then
              SQUIDLOGUSER="${res##*:}"
            fi
        else
            printf "Squidmill is neither manually configured nor Squid configuration is found"
            failure "not configured"
            echo
            exit 1
        fi
    fi

    if ! [ -d `dirname "$SQUIDLOGFILE"` ]; then
      mkdir -p -m0755 `dirname "$SQUIDLOGFILE"`
      chown $SQUIDLOGUSER `dirname "$SQUIDLOGFILE"`
    fi
    if ! [ -f "$SQUIDLOGFILE" ]; then
      touch "$SQUIDLOGFILE"
      chown $SQUIDLOGUSER "$SQUIDLOGFILE"
    fi

    if ! [ -d `dirname "$DBFILE"` ]; then
      mkdir -p -m0755 `dirname "$DBFILE"`
      chown $SQUIDLOGUSER `dirname "$DBFILE"`
    fi

    start_daemon --pidfile "$PIDFILE" \
                 --make-pidfile \
                 --lockfile "$LOCKFILE" \
                 --displayname squidmill \
                 -- /bin/su -s /bin/sh -l "$SQUIDLOGUSER" \
                            -c "'/usr/sbin/squidmill -d \"$DBFILE\" -B 1 -F \"$SQUIDLOGFILE\"'"
}

stop()
{
    stop_daemon --pidfile "$PIDFILE" \
                --lockfile "$LOCKFILE" \
                --displayname squidmill \
                -- /bin/su
}

case "$1" in
    start)
      start
        ;;
    stop|condstop)
      stop
      ;;
    status)
      status --pidfile "$PIDFILE" --displayname squidmill /bin/su
      ;;
    restart|reload|condrestart|condreload)
        stop
        start
        ;;
    *)
        msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
        RETVAL=1
esac

exit $RETVAL
