#!/bin/sh
# Begin /etc/init.d/
# DNSMASQ is a simple DNS+DHCP server
#
# Notes for Vector Linux
# The configuration file is : /etc/dnsmasq.conf
# The data files used by dnsmasq are:
#    /etc/hosts
#    /etc/resolv.conf.dnsmasq
#    /etc/resolv.conf
#
# The dnsmasq is customized to work this way ...
#
# Case A: Without dnsmasq ...
# - /etc/resolv.conf points to the real DNS, 
#   used directly by the system
# That's it.
#
# Case B: With dnsmasq
# - /etc/resolv.conf points to 127.0.0.1 for the system 
# - the dnsmasq running on 127.0.0.1 answers the system.
#   It reads the data from /etc/hosts and queries the real DNS.
# - /etc/resolv.conf.dnsmasq points to the real DNS,
#   used by the dnsmasq
# - If you dial up using a modem, dnsmasq automatically 
#   uses /etc/ppp/resolv.conf too
#
# The script /etc/rc.d/init.d/dnsmasq (this one) switch
# /etc/resolv.conf and /etc/resolv.conf.dnsmasq when it starts/stops.
# There is a potential problem if unaware configurators/users
# change the /etc/resolv.conf when dnsmasq is running. 
# So ... take care ;-)
#
# (c) Eko M. Budi for Vector Linux
# License : GNU GPL


# Include the functions declared in the /etc/rc.d/functions file
source /etc/rc.d/functions

# path to binary
ROOT="/usr/sbin"
# name of binary to run
APP="dnsmasq"
#runtime options
#OPT=""

#server name & description
SERVER="DNSMASQ server"

RESOLV_SYSTEM=/etc/resolv.conf
RESOLV_DNSMASQ=/etc/resolv.conf.dnsmasq

service_start()
{
    # if old resolv.conf contains a real nameserver, copy it
    if [ -r $RESOLV_SYSTEM ]; then
	if grep "nameserver" $RESOLV_SYSTEM | grep -qv "127.0.0.1"; then
	    cp $RESOLV_SYSTEM $RESOLV_DNSMASQ
	fi
    fi
    HOST_NAME=`cat /etc/HOSTNAME`
    echo "search ${HOSTNAME#*.}" > $RESOLV_SYSTEM
    echo "nameserver 127.0.0.1" >> $RESOLV_SYSTEM 
    loadproc $ROOT/$APP $OPT
}

service_stop()
{
    killproc $ROOT/$APP

    # If resolf.conv set to 127.0.0.1, overwrite back
    # If not, somebody have changed it. 
    # So leave it, so we can use it next time
    if [ -r $RESOLV_DNSMASQ ]; then
	if grep -qe "nameserver *127.0.0.1" $RESOLV_SYSTEM; then
	    cp $RESOLV_DNSMASQ $RESOLV_SYSTEM
	fi
    fi
}


case "$1" in
        start)
                echon "Starting $SERVER............"
                service_start
                ;;
        reload)
                echon "Reloading $SERVER..........."
                checkloadproc $ROOT/$APP $OPT
                ;;
        stop)
                echon "Stopping $SERVER............"
                service_stop
                ;;
        restart)
                $0 stop
                /bin/sleep 1
                $0 start
                ;;
        status)
                statusproc $ROOT/$APP
                ;;
        *)
                echo "Usage: $0 {start|stop|reload|restart|status}"
                exit 1
        ;;

esac

# End /etc/init.d/
