#!/bin/sh -e

$DEBIAN_SCRIPT_DEBUG || set -v -x 

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=wwwoffled
PROGRAM=/usr/bin/wwwoffle
DAEMON=/usr/sbin/$NAME
CONFIG=/etc/wwwoffle/wwwoffle.conf

test -f $DAEMON || exit 0

mode=offline
# ISDN and diald can be in autodial mode
if isdnctrl dialmode all 2>/dev/null |grep "[^ ]: auto" >/dev/null; then
  mode=autodial
elif ps ax |grep -v grep |grep /usr/sbin/diald; then
  mode=autodial
fi
# Or, in the case of a restart the wwwoffled maybe was already online.
# That's important if anacron starts logrotate during an online session.
if ps acx|grep wwwoffled>/dev/null && wwwoffle -offline|grep -v Already>/dev/null 
then
  wwwoffle -online 2>&1 >/dev/null
  mode=online
fi

case "$1" in
  start)
	# Check if the cache dir is intact. According to the Debian Policy 
	# the cache dir may be deleted and has to recreate itself automatically.
	install -d -D -o proxy -g proxy /var/cache/wwwoffle
	test -L /var/cache/wwwoffle/html \
	  || ln -sf /usr/share/wwwoffle/html /var/cache/wwwoffle/html
	#test -L /var/cache/wwwoffle/monitor \
	#  || ln -sf ../../lib/wwwoffle/monitor /var/cache/wwwoffle/monitor
	echo -n "Starting HTTP cache proxy server: $NAME"
	if start-stop-daemon --start  --exec $DAEMON -- -c $CONFIG; then 
	  echo "."
	  if [ "$mode" != "offline" ]; then
	    $PROGRAM -c $CONFIG -$mode
	  fi
	else 
	  echo "...failed."
	fi
	;;
  stop)
	echo -n "Stopping HTTP cache proxy server: $NAME"
	if start-stop-daemon --stop  --quiet --exec $DAEMON; then 
	  echo "."
	else 
	  echo "...failed."
	fi
	;;
  force-restart|restart)
	$0 stop
	$0 start
	if [ "$mode" != "offline" ]; then
	  $PROGRAM -c $CONFIG -$mode
	fi
	;;
  force-reload)
	$0 stop
	$0 start
	if [ "$mode" != "offline" ]; then
	  $PROGRAM -c $CONFIG -$mode
	fi
	;;
  reload)
	echo -n "Reloading $NAME configuration files..."
    	if start-stop-daemon --stop  --signal 1 --quiet --exec $DAEMON; then 
      	  echo "done."
    	else 
      	  echo "failed."
    	fi
    	;;
  *)
	echo "Usage: /etc/init.d/$NAME {start|stop|reload|restart|force-restart|force-reload}"
	exit 1
	;;
esac

exit 0
