#!/bin/sh
#
# dnscache plugin
# Author: Yuuki Harano <masm@flowernet.gr.jp>
# Time-stamp: <04/10/23 22:47:09 jado@sheira>
#
# Copyright (c) 2004 Yuuki Harano
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#

# dnscache depends on daemontools
DNSCACHEDIR=/service/dnscache
DNSCACHEROOTS=$DNSCACHEDIR/root/servers/@
DNSCACHEENV=$DNSCACHEDIR/env

# Additional settings going into /etc/network.conf:
#
# DNSROOT : dnscache root server list [+ (from DHCP)|IPaddr...]

DNSCACHEDEV=$PLUGINSTATE/dnscache.devices

dnscache_check ()
{
    if [ -s $DNSCACHEDEV -o -s $DNSCACHEDEV.N ]; then
        echo "others"
    else
        echo "offline"
    fi
}

dnscache_update ()
{
    if [ ! -x /command/svc -o ! -d $DNSCACHEDIR ]; then
	echo "Please install daemontools and dnscache to work with DNSROOT."
	return
    fi

    echo -n > $DNSCACHEROOTS
    if [ ! -s $DNSCACHEDEV ]; then
	rm -f $DNSCACHEENV/FORWARDONLY
    else
	echo 1 > $DNSCACHEENV/FORWARDONLY
	for ns in `/usr/bin/grep -v '^#' $DNSCACHEDEV | sort | uniq`; do
	    echo "$ns" >> $DNSCACHEROOTS
	done
    fi

    if [ "$1" = "others" ]; then
	/command/svc -t $DNSCACHEDIR
    fi
}

# Variables definition

dnscache_VARS="DNSROOT:domain_name_servers"

# Script on starting

dnscache_start ()
{
    touch $DNSCACHEDEV
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $DNSCACHEDEV > $DNSCACHEDEV.N

    if [ -n "$DNSROOT" ]; then
	echo "# $1 begin" >> $DNSCACHEDEV.N
	for s in $DNSROOT; do
	    echo "$s" >> $DNSCACHEDEV.N
	done
	echo "# $1 end device" >> $DNSCACHEDEV.N
    fi

    local MODE=`dnscache_check`
    mv $DNSCACHEDEV.N $DNSCACHEDEV
    dnscache_update $MODE
}

# Script on stopping

dnscache_stop ()
{
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $DNSCACHEDEV > $DNSCACHEDEV.N

    local MODE=`dnscache_check`
    mv $DNSCACHEDEV.N $DNSCACHEDEV
    dnscache_update $MODE
}
