#!/bin/sh
#
# dnscache plugin
# Author: Yuuki Harano <masm@flowernet.gr.jp>
# Time-stamp: <2005/08/13 18:17:25 jado@spica>
#
# Copyright (c) 2004,2005 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
DNSCACHESERVERSDIR=$DNSCACHEDIR/root/servers
DNSCACHEENV=$DNSCACHEDIR/env

# Additional settings going into /etc/network.conf:
#
# DNSCACHE : dnscache configuration.
#   DNSCACHE:  domain[,domain...]:server[,server...]
#   domain: domain name or "@"
#   server: IPaddr or "+" (from DHCP)
#   

DNSCACHEDEV=$PLUGINSTATE/dnscache.devices

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

    rm -f $DNSCACHESERVERSDIR/*
    rm -f $DNSCACHEENV/FORWARDONLY

    touch $DNSCACHESERVERSDIR/@

    cat $DNSCACHEDEV | /usr/bin/sed -e 's/#.*//' -e '/^[ 	]*$/d' | \
    while read x; do
	dm=
	sv=
	case "$x" in
	*:*)
	    dm=`echo "$x" | /usr/bin/sed -e 's/:.*//'`
	    sv=`echo "$x" | /usr/bin/sed -e 's/.*://'`
	    ;;
	*)
	    dm='@'
	    sv=$x
	    ;;
	esac

	for d in `echo $dm | /usr/bin/sed -e 's/,/ /g'`; do
	    echo $sv | tr ',' '\012' >> $DNSCACHESERVERSDIR/$d
	done
	
	echo 1 > $DNSCACHEENV/FORWARDONLY
    done

    /command/svc -t $DNSCACHEDIR
}

# Variables definition

dnscache_VARS="DNSCACHE"
# DHCP_DNS and DHCP_DOMAIN are also used.

# Script on starting

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

    (
	dhcp_dns=`echo $DHCP_DNS | /usr/bin/sed -e 's/ /,/g'`
	dhcp_domain=$DHCP_DOMAIN
	echo "# $1 begin"
	for x in $DNSCACHE; do
	    case "$x" in
	    *:*)
		dm=`echo "$x" | /usr/bin/sed -e "s/:.*//" | @SED@ -e "s|+|$dhcp_domain|g"`
		sv=`echo "$x" | /usr/bin/sed -e "s/.*://" | @SED@ -e "s|+|$dhcp_dns|g"`
		echo "$dm:$sv"
		;;
	    *)
		echo "$x" | /usr/bin/sed -e "s|+|$dhcp_dns|g"
		;;
	    esac
	done
	echo "# $1 end device"
    ) >> $DNSCACHEDEV.N
    
    mv $DNSCACHEDEV.N $DNSCACHEDEV
    dnscache_update
}

# Script on stopping

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