#!/bin/sh
#< Simple script to control the Trivial File Transfer Protocol Daemon (tftpd)

# Kevin Waldron 27/10/05

PROGNAME=`basename $0`
PS=/bin/ps
GREP=/bin/grep
WC=/usr/bin/wc
PKILL=/usr/bin/pkill
ECHO=/bin/echo
TFTPD=/usr/sbin/in.tftpd

usage() {
   ${ECHO} "Usage: ${PROGNAME} [ start | stop | restart | status ]"
   exit 1
}

if [ "${#}" -ne "1" ]; then
   usage
fi

case ${1} in
   start)   NUM_TFTP=`${PS} -ef | ${GREP} "in\.tftpd" | ${GREP} -v grep | ${WC} -l`
            if [ "${NUM_TFTP}" -ge "1" ]; then
               ${ECHO} "Error: in.tftpd already running!" >&2
               exit 2
            else
               ${TFTPD} -l -c -s /tftpboot
               if [ "${?}" -ne "0" ]; then
                  ${ECHO} "Error: in.tftpd was not started successfully" >&2
                  exit 3
               else
                  ${ECHO} "in.tftpd started successfully"
               fi
            fi
            ;;
   stop)    NUM_TFTP=`${PS} -ef | ${GREP} "in\.tftpd" | ${GREP} -v grep | ${WC} -l`
            if [ "${NUM_TFTP}" -lt "1" ]; then
               ${ECHO} "Error: in.tftpd already stopped!" >&2
               exit 2
            else
               ${PKILL} in.tftpd
               if [ "${?}" -ne "0" ]; then
                  ${ECHO} "Error: in.tftpd was not stopped successfully" >&2
                  exit 3
               else
                  ${ECHO} "in.tftpd stopped successfully"
               fi
            fi
            ;;
   restart) ${0} stop
            ${0} start
            ;;
   status)  NUM_TFTP=`${PS} -ef | ${GREP} "in\.tftpd" | ${GREP} -v grep | ${WC} -l`
            if [ "${NUM_TFTP}" -lt "1" ]; then
               ${ECHO} "in.tftpd status: stopped"
            else
               ${ECHO} "in.tftpd status: started"
            fi
            ;;
   *)       usage
            ;;
esac

exit 0