#!/usr/bin/env bash
#
# MacPorts generated daemondo support script
#

#
# Init
#
prefix=/opt/local
if [ -f "${prefix}/etc/adblock2privoxy/ADBLOCK2PRIVOXY.env" ]; then
	set -a
	. <(grep -E -o -e '^[[:alnum:]_]+=[^[:space:];]+$' "/opt/local/etc/adblock2privoxy/ADBLOCK2PRIVOXY.env" | grep -E -v '^[[:space:]]*(#|$)|\$\(|`')
	set +a
fi
ADBLOCK2PRIVOXY_CSS_SERVER="${ADBLOCK2PRIVOXY_CSS_SERVER:-127.0.0.1:8119}"

#
# Start
#
Start()
{
	( IFS=$'\n' ADBLOCK2PRIVOXY_BLOCKLIST=($(grep -v -e '^ *#' < "${prefix}/etc/adblock2privoxy/adblock2privoxy_blocklist.txt" \
		| while read -r t; do if "${prefix}/bin/wget" --max-redirect=0 -S --spider "${t}" 2>&1 | grep -q 'HTTP/1.1 200 OK'; then echo "${t}"; fi done)); \
	/bin/test -f "${prefix}/etc/adblock2privoxy/privoxy/ab2p.task" \
	&& "${prefix}/bin/adblock2privoxy" -t "${prefix}/etc/adblock2privoxy/privoxy/ab2p.task" \
	|| "${prefix}/bin/adblock2privoxy" -p "${prefix}/etc/adblock2privoxy/privoxy" \
		-w "${prefix}/etc/adblock2privoxy/css" \
		-d "${ADBLOCK2PRIVOXY_CSS_SERVER}"  \
		"${ADBLOCK2PRIVOXY_BLOCKLIST[@]}" \
	) && "${prefix}/bin/port" reload privoxy
}

#
# Stop
#
Stop()
{
	/usr/bin/kill -SIGUSR1 "$(/usr/bin/pgrep -u root adblock2privoxy)" 2>/dev/null
}

#
# Restart
#
Restart()
{
	Stop
	Start
}

#
# Run
#
Run()
{
case $1 in
  start  ) Start   ;;
  stop   ) Stop    ;;
  restart) Restart ;;
  *      ) echo "$0: unknown argument: $1";;
esac
}

#
# Run a phase based on the selector
#
Run $1

