description "ISC DHCP IPv4 server"
author "Stéphane Graber <stgraber@ubuntu.com>"

start on runlevel [2345]
stop on runlevel [!2345]

pre-start script
    if [ ! -f /etc/default/isc-dhcp-server ]; then
        echo "/etc/default/isc-dhcp-server does not exist! - Aborting..."
        echo "Run 'dpkg-reconfigure isc-dhcp-server' to fix the problem."
        stop
        exit 0
    fi
    . /etc/default/isc-dhcp-server

    if [ -f /etc/ltsp/dhcpd.conf ]; then
        CONFIG_FILE=/etc/ltsp/dhcpd.conf
    else
        CONFIG_FILE=/etc/dhcp/dhcpd.conf
    fi
    if [ ! -f $CONFIG_FILE ]; then
        echo "$CONFIG_FILE does not exist! - Aborting..."
        echo "Please create and configure $CONFIG_FILE to fix the problem."
        stop
        exit 0
    fi

    if ! ip netns exec fw dhcpd -user dhcpd -group dhcpd -t -q -4 -cf $CONFIG_FILE > /dev/null 2>&1; then
        echo "dhcpd self-test failed. Please fix the config file."
        echo "The error was: "
        ip netns exec fw dhcpd -user dhcpd -group dhcpd -t -4 -cf $CONFIG_FILE
        stop
        exit 0
    fi
end script

respawn
script
    if [ -f /etc/ltsp/dhcpd.conf ]; then
        CONFIG_FILE=/etc/ltsp/dhcpd.conf
    else
        CONFIG_FILE=/etc/dhcp/dhcpd.conf
    fi

    . /etc/default/isc-dhcp-server

    # Allow dhcp server to write lease and pid file as 'dhcpd' user
    mkdir -p /var/run/dhcp-server
    chown dhcpd:dhcpd /var/run/dhcp-server

    # The leases files need to be root:root even when dropping privileges
    [ -e /var/lib/dhcp/dhcpd.leases ] || touch /var/lib/dhcp/dhcpd.leases
    chown root:root /var/lib/dhcp /var/lib/dhcp/dhcpd.leases
    if [ -e /var/lib/dhcp/dhcpd.leases~ ]; then
        chown root:root /var/lib/dhcp/dhcpd.leases~
    fi

    exec ip netns exec fw dhcpd -user dhcpd -group dhcpd -f -q -4 -pf /run/dhcp-server/dhcpd.pid -cf $CONFIG_FILE $INTERFACES
end script
