#! /bin/sh

UDHCPD=udhcpd
TMP_DIR=/tmp

BASE_FILE=${TMP_DIR}/${UDHCPD}.

start_dhcp() {
    # Check if the parameter $1 exists
    
    $UDHCPD ${BASE_FILE}$1.conf
    echo "Starting udhcpd on interface $1"

}

stop_dhcpd() {
    # Check if the deamon is running by checking if the pid file exists
    if [ -e ${BASE_FILE}$1.pid ]
    then
        pid=`cat ${BASE_FILE}$1.pid`
        kill $pid
        echo "Killing udhcpd on interface $1 with pid $pid"
                                #rm ${BASE_FILE}$1.pid
    fi
}

get_dhcpd_status() {
    if [ -e ${BASE_FILE}$1.pid ]
    then
        return 1
    else
        return 0
    fi      
}

generate_udhcpd_config_file() {
    # Parameters:
    # Interface tabletIP Netmask [router] [dns1] [dns2] ...
    CONF_FILE=${BASE_FILE}$1.conf
    
    echo "# Automatically generated by pc-connectivity-manager" > $CONF_FILE
    
    # Put the pid file
    echo "pidfile ${BASE_FILE}$1.pid" >> $CONF_FILE
    
    # Put the interface
    echo "interface $1" >> $CONF_FILE
    shift
    
    # Lease server address
    echo "static_lease 00:00:00:00:00:00 $1" >> $CONF_FILE
    
    # Put the start ip to give
    IP_PREFIX="$(get_net_addr $1 $2)"
    IP_PREFIX=${IP_PREFIX%.0}
    echo "start ${IP_PREFIX}.14" >> $CONF_FILE
    
    # Put the end ip to give
    echo "end ${IP_PREFIX}.250" >> $CONF_FILE
    shift
    
    # Put the netmask
    echo "option subnet $1" >> $CONF_FILE
    
    
    # If there is one more parameter, put it as the router address
    if [ $# -gt 1 ]
    then
        shift
        echo "option router $1" >> $CONF_FILE
    fi
    
    if [ $# -gt 1 ]
    then
        shift
        # Put all the other parameters as dns
        while [ "$1" != "" ]; do
            echo "option dns $1" >> $CONF_FILE
        
            shift
        done
    fi
    

}

get_net_addr() {
    IP=$1
    MASK=$2
    
    NETWORK_IP=""
    for i in $(seq 4)
    do
        OCT=`echo $IP | cut -d. -f$i`
        MASK_OCT=`echo $MASK | cut -d. -f$i`
        NET=$(($OCT & $MASK_OCT))
        NETWORK_IP=${NETWORK_IP}${NET}
        if [ $i -ne 4 ]
        then
            NETWORK_IP=${NETWORK_IP}.
        fi
    done

    echo $NETWORK_IP
}

case "$1" in
start)
    shift
    generate_udhcpd_config_file $@
    start_dhcp $1
    ;;
stop)
    stop_dhcpd $2
    ;;
status)
    get_dhcpd_status $2
    exit $?
    ;;
*)
    ;;
esac
    
