#!/bin/sh

# PROVIDE: privoxy
# REQUIRE: DAEMON
# BEFORE: LOGIN
#
# This rc script understands the following variables
# which are read from /etc/rc.conf:
#
# privoxy_enable  (bool): Set to "NO" by default.
#                         Set it to "YES" to enable Privoxy.
# privoxy_config   (str): Privoxy's configuration file. Default is:
#                         %%PREFIX%%/etc/privoxy/config.
# privoxy_flags    (str): List of additional Privoxy options you want
#                         to use. None set by default.
# privoxy_pidfile  (str): Default is /var/run/privoxy/privoxy.pid.
# privoxy_user     (str): Privoxy Daemon user. Default is privoxy.
#
# Usage:
# %%PREFIX%%/etc/rc.d/privoxy [fast|force|one](start|stop|restart|rcvar|status|poll)

. /etc/rc.subr

name="privoxy"
rcvar=privoxy_enable
load_rc_config ${name}

: ${privoxy_enable="NO"}
: ${privoxy_config="%%PREFIX%%/etc/privoxy/config"}
: ${privoxy_logdir="/var/log/privoxy"}
: ${privoxy_user="privoxy"}
: ${privoxy_piddir="/var/run/privoxy"}
: ${privoxy_pidfile="${privoxy_piddir}/privoxy.pid"}

privoxy_prestart () {
    if [ ! -e "${privoxy_config}" ]; then
        echo "config file not found. Copying the example file to ${privoxy_config}."
        cp %%PREFIX%%/share/examples/privoxy/config "${privoxy_config}"
        chown "${privoxy_user}:${privoxy_user}" "${privoxy_config}";
    fi
    actionfile="%%PREFIX%%/etc/privoxy/match-all.action"
    if [ ! -e "${actionfile}" ]; then
        echo "${actionfile} not found. Copying the example file."
        cp %%PREFIX%%/share/examples/privoxy/match-all.action "${actionfile}"
        chown "${privoxy_user}:${privoxy_user}" "${actionfile}"
    fi
    if [ ! -e "${privoxy_logdir}" ]; then
        echo "${privoxy_logdir} not found. Creating ..."
        mkdir "${privoxy_logdir}"
        chown "${privoxy_user}:${privoxy_user}" "${privoxy_logdir}"
        chmod 0750 "${privoxy_logdir}"
    fi
    if [ ! -d "${privoxy_piddir}" ]; then
        mkdir -p "${privoxy_piddir}"
        chown "${privoxy_user}:${privoxy_user}" "${privoxy_piddir}"
    fi
}

start_precmd="privoxy_prestart"

command="%%PREFIX%%/sbin/privoxy"
command_args="${privoxy_flags} --pidfile ${privoxy_pidfile} ${privoxy_config}"

run_rc_command "$1"
