#!/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

if grep -qsx ppp /etc/wwwoffle/wwwoffle.options; then
    # a whole lot of logic to determine what mode wwwoffle should run in...
    mode=offline
    # ISDN and diald can be in autodial mode
    # find default route
    WWWOFFLEDEFROUTEIF=`netstat -rn | awk '/^0\.0\.0\.0 / {print $8}'`
    if [ `expr "$WWWOFFLEDEFROUTEIF" : i` -eq 1 ]; then # default route via ISDN
        if isdnctrl status $WWWOFFLEDEFROUTEIF >/dev/null 2>&1; then
            mode=online
        elif isdnctrl dialmode $WWWOFFLEDEFROUTEIF 2>/dev/null |
                            grep auto >/dev/null; then
            # ISDN interface is in autodial mode
            mode=autodial
        fi
    elif pgrep '^diald$' >/dev/null; then
        # diald is running, hence also autodial
        mode=autodial
    elif pgrep '^pp(tp|poe)$' >/dev/null; then
        # pptp or pppoe is running (for ADSL), hence always online
        mode=online
    fi
else
    # wwwoffle not configured to go over dialup, so assume online
    mode=online
fi

case "$1" in
  start)
	echo -n "Starting HTTP cache proxy server: $NAME "
	# 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/http		\
	    /var/cache/wwwoffle/lastout		\
	    /var/cache/wwwoffle/lasttime	\
	    /var/cache/wwwoffle/local		\
	    /var/cache/wwwoffle/outgoing	\
	    /var/cache/wwwoffle/prevtime1	\
	    /var/cache/wwwoffle/finger		\
	    /var/cache/wwwoffle/ftp		\
	    /var/cache/wwwoffle/search/htdig/db	\
	    /var/cache/wwwoffle/search/htdig/db-lasttime \
	    /var/cache/wwwoffle/search/htdig/tmp \
	    /var/cache/wwwoffle/search/mnogosearch/db \
	    /var/cache/wwwoffle/search/namazu/db
        # mark the directory as a cache directory
        if [ ! -f /var/cache/wwwoffle/CACHEDIR.TAG ]; then
            cat > /var/cache/wwwoffle/CACHEDIR.TAG << 'EOF'
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by wwwoffle.
# For information about cache directory tags, see:
#       http://www.brynosaurus.com/cachedir/
EOF
        fi

	msg=" in /var/cache/wwwoffle/search"
	for i in htdig mnogosearch namazu; do
	    if [ ! -L /var/cache/wwwoffle/search/$i/conf ]; then
		echo "restoring $i/conf    symlink$msg"; msg=''
		rm -f /var/cache/wwwoffle/search/$i/conf
		ln -s /etc/wwwoffle/$i /var/cache/wwwoffle/search/$i/conf
	    fi
	    if [ ! -L /var/cache/wwwoffle/search/$i/scripts ]; then
		echo "restoring $i/scripts symlink$msg"; msg=''
		rm -f /var/cache/wwwoffle/search/$i/scripts
		ln -s /usr/share/wwwoffle/search/$i /var/cache/wwwoffle/search/$i/scripts
	    fi
	done
	if [ ! -L /var/cache/wwwoffle/html ];  then
		if [ -e /var/cache/wwwoffle/html ]; then
			mv -f /var/cache/wwwoffle/html /var/cache/wwwoffle/html.x
		fi
		ln -sf /etc/wwwoffle/html /var/cache/wwwoffle/html
	fi
        if [ ! -L /var/cache/wwwoffle/monitor ]; then
            if [ -d /var/cache/wwwoffle/monitor ]; then
                (
                  echo "  moving /var/cache/wwwoffle/monitor to /var/lib/wwwoffle/monitor"
                  cd /var/cache/wwwoffle/monitor;
		  mv * /var/lib/wwwoffle/monitor 2>/dev/null || true
                )
            fi
            rm -rf /var/cache/wwwoffle/monitor
            echo "  creating /var/cache/wwwoffle/monitor symlink"
            ln -sf ../../lib/wwwoffle/monitor /var/cache/wwwoffle/monitor
        fi
	# fix namazu NMZ files; they're in /etc, but symlinked to /var/cache
	(
	  cd /etc/wwwoffle/namazu
	  for i in NMZ.body NMZ.foot NMZ.head NMZ.result.normal NMZ.result.short NMZ.tips; do
		if [ ! -s /var/cache/wwwoffle/search/namazu/db/$i ]; then
			ln -s /etc/wwwoffle/namazu/$i /var/cache/wwwoffle/search/namazu/db/$i
		fi
	  done
	)
        TEMPFILE=`tempfile -p WWWOFFLE`
        set +e
        start-stop-daemon --start  --exec $DAEMON -- -c $CONFIG >$TEMPFILE 2>&1
        RC=$?
	# If listening to IPv6 socket, then binding to the IPv4 socket _will_ fail
	# Ignore those warning lines
	if grep 'Warning: Failed to bind IPv4 server socket to.*Address already in use' $TEMPFILE >/dev/null &&
	   grep 'Warning: Cannot create HTTP IPv4 server socket .but the IPv6 one might accept IPv4 connections' $TEMPFILE >/dev/null; then
	  fgrep -v 'Important: WWWOFFLE Demon Version 
Important: Detached from terminal and changed pid to
Information: WWWOFFLE Read Configuration File
Information: Running with uid=
Warning: Failed to bind IPv4 server socket
Warning: Cannot create HTTP IPv4 server socket
Warning: Cannot create WWWOFFLE IPv4 server socket' $TEMPFILE
          echo ""
          echo "    Note: when using IPv6, it is recommended to disable the IPv4 socket with"
          echo "    	bind-ipv4 = none"
          echo "    in /etc/wwwoffle/wwwoffle.conf as the IPv6 socket will also listen to IPv4."
	else
	  fgrep -v 'Important: WWWOFFLE Demon Version 
Important: Detached from terminal and changed pid to
Information: WWWOFFLE Read Configuration File
Information: Running with uid=' $TEMPFILE
	fi
        rm -f $TEMPFILE
        set -e
        if [ $RC -eq 0 ]; then
	  if [ "$mode" = "offline" ]; then
            echo "(offline mode) done."
          else
	    $PROGRAM -c $CONFIG -$mode
	  fi
	else 
	  echo "...failed."
	fi
        if grep -qsx nocheckconf /etc/wwwoffle/wwwoffle.options; then
          if grep '^[^#]*://.*/$' $CONFIG; then
            printf '\a'
            cat << 'EOF'

Note: you have URL patterns in your wwwoffle.conf that end with a '/'.
This may not do as you expect: '*:/*.foo/' matches only the path '/',
while while '*:/*.foo' and '*:/*.foo/*' both match all URLs on the host.

(To prevent this message, add a line with exactly "nocheckconf" to
/etc/wwwoffle/wwwoffle.options .)

EOF
            sleep 6
          fi
        fi
	;;
  stop)
	echo -n "Stopping HTTP cache proxy server: $NAME"
	TEMPFILE=`tempfile -p WWWOFFLE`
	$PROGRAM -c $CONFIG -kill >$TEMPFILE 2>&1 || true
	if grep 'Fatal:' $TEMPFILE >/dev/null; then
	  if grep 'Warning: Failed to create and connect client socket.' $TEMPFILE >/dev/null; then
	    rm -f $TEMPFILE
	    echo "...can't connect to control socket."
	    echo -ne "\tTrying to signal daemon process"
	    if start-stop-daemon --stop  --signal 15 --quiet --exec $DAEMON; then 
	      echo "...done."
	      exit 0
	    else 
	      echo "...failed, daemon was not running."
	      exit 1
	    fi
	  fi
	  echo "... failed:"
	  sed 's,^,\t,' $TEMPFILE
	  rm -f $TEMPFILE
	  exit 1
	fi
	rm -f $TEMPFILE
	for i in 1 2 3 4 5; do
	  if pgrep wwwoffled >/dev/null 2>&1; then
	    sleep 1
	    echo -n "."
	  else
	    echo " ok."
	    exit 0
	  fi
	done
	if start-stop-daemon --stop  --quiet --exec $DAEMON; then 
	  echo " ok."
	  exit 0
	fi
	echo " stopping failed!"
	exit 1
	;;
  force-restart|restart|force-reload)
        newmode="$mode"
	# The wwwoffled maybe was already online.
        if pgrep '^wwwoffled$' >/dev/null; then
            if wwwoffle -status -c $CONFIG | grep -qs online; then
                newmode=online
            elif wwwoffle -status -c $CONFIG | grep -qs offline; then
                newmode=offline
            else
                newmode=autodial   # lucky guess?
            fi
        fi
	$0 stop
	sleep 2
	$0 start
        # if wwwoffle wasn't in the default startup mode, change it
	if [ "$newmode" != "$mode" ]; then
		$PROGRAM -c $CONFIG -$newmode
	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
