#!/bin/bash

#db configuration show tftpd
#Database: configuration
#Key: tftpd
#PROP: status 	VALUES: enabled/disabled
#PROP: access 	VALUES: private/public/localhost
#PROP: log 	VALUES: normal/verbose/disabled
#PROP: user 	VALUES: root/nobody 			(or any other valid user)
#PROP: privelege VALUES: ro/rw
#PROP: timeout: 	VALUES: default/300 			(secounds, 900 is the default)
#PROP: UDPPort:	VALUES: 69
#PROP: directory VALUES: /tftpboot 			(or any other directory)
#PROP: refuse	VALUES:	<tftp-option>	(any tftp option that you need to disable)

TFTPD_STATUS=$(/sbin/e-smith/db configuration getprop tftpd status);
if [ $TFTPD_STATUS == "enabled" ]; then
    TFTPD_ACCESS=$(/sbin/e-smith/db configuration getprop tftpd access);
    TFTPD_LOG=$(/sbin/e-smith/db configuration getprop tftpd log);
    TFTPD_USER=$(/sbin/e-smith/db configuration getprop tftpd user);
    TFTPD_PRIVILEGE=$(/sbin/e-smith/db configuration getprop tftpd privilege);
    TFTPD_TIMEOUT=$(/sbin/e-smith/db configuration getprop tftpd timeout);
    TFTPD_UDPPORT=$(/sbin/e-smith/db configuration getprop tftpd UDPPort);
    TFTPD_DIRECTORY=$(/sbin/e-smith/db configuration getprop tftpd directory);
    TFTPD_REFUSE=$(/sbin/e-smith/db configuration getprop tftpd refuse);
    TFTPD_BLKSIZE=$(/sbin/e-smith/db configuration getprop tftpd blksize);

    # If BLKSIZE is set
    if [ ! -z $TFTPD_BLKSIZE ]; then
    #echo "Block size $TFTPD_BLKSIZE"
        if   [ "$TFTPD_BLKSIZE" -le "512" ] ; then
            TFTPD_BLKSIZE=1500;
        elif [ "$TFTPD_BLKSIZE" -ge "65464" ] ; then
            TFTPD_BLKSIZE=65464;
        fi
        #echo "Now we have $TFTPD_BLKSIZE"
    fi
    #echo "Block size is $TFTPD_BLKSIZE"

    TFTPD_ACCESS_SETTING="127.0.0.1";
    if [ $TFTPD_ACCESS == "public" ]; then
	TFTPD_ACCESS_SETTING="0.0.0.0"; 
    elif [ $TFTPD_ACCESS == "private" ]; then 
	TFTPD_ACCESS_SETTING=$(/sbin/e-smith/db configuration get LocalIP);
    fi

    TFTPD_LOG_SETTING="-v";
    if [ $TFTPD_LOG == "verbose" ]; then
	TFTPD_LOG_SETTING="-vv";
    elif [ $TFTPD_LOG == "disabled" ]; then
	TFTPD_LOG_SETTING="";
    fi

    TFTPD_PRIVILEGE_SETTING=""
    if [ $TFTPD_PRIVILEGE == "rw" ]; then
	TFTPD_PRIVILEGE_SETTING="-c";
    fi

    TFTPD_TIMEOUT_SETTING=""
    if [ $TFTPD_TIMEOUT != "default" ]; then
	TFTPD_TIMEOUT_SETTING="-t $TFTPD_TIMEOUT";
    fi

    TFTPD_REFUSE_SETTING=""
    if [ "$TFTPD_REFUSE" != "" ]; then
	TFTPD_REFUSE_SETTING="-r $TFTPD_REFUSE";
    fi

    TFTPD_BLKSIZE_SETTING=""
    if [ "$TFTPD_BLKSIZE" != "" ]; then
	TFTPD_BLKSIZE_SETTING="-B $TFTPD_BLKSIZE";
    fi

    cd /
    exec 2>&1
    exec    udpsvd	-h $TFTPD_LOG_SETTING \
			$TFTPD_ACCESS_SETTING $TFTPD_UDPPORT \
    	    in.tftpd 	$TFTPD_LOG_SETTING $TFTPD_PRIVILEGE_SETTING \
			-u $TFTPD_USER $TFTPD_TIMEOUT_SETTING $TFTPD_REFUSE_SETTING $TFTPD_BLKSIZE_SETTING -s $TFTPD_DIRECTORY
else
    /usr/bin/runsvctrl down .
fi
