#!/bin/sh
### BEGIN INIT INFO
# Provides:          iperf3
# Required-Start:    $local_fs $network $remote_fs $syslog
# Required-Stop:     $local_fs $network $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: <Enter a short description of the software>
# Description:       <Enter a long description of the software>
#                    <...>
#                    <...>
### END INIT INFO

# Author: PICCORO Lenz McKAY <mckaygerhard@gmail.com>

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="network bandwidth measurement v3"
NAME=iperf3
DAEMON=/usr/bin/iperf3
DAEMON_ARGS=""
DAEMON_START_INI=false
PIDFILE=/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions


case "$1" in
  start)

if [ "$DAEMON_START_INI" != 1 ]; then
	log_success_msg "$DESC not enabled, edit at /etc/default/$NAME"
	exit 0
fi


	log_daemon_msg "Starting $DESC" "$NAME"

                 pid="$(pidof iperf3)"
                 if [ ! -z "$pid" ] ; then
                     log_daemon_msg "an iperf3 are running or not managed" "$NAME"
                     exit 1
                 fi
                 start-stop-daemon --start --quiet --background --make-pidfile --pidfile $PIDFILE  --no-close --startas $DAEMON --name $NAME --exec $DAEMON -- -s -D $DAEMON_ARGS >>  /var/log/$NAME.log 2>&1
                 status=$?
                 pid="$(pidof iperf3)"
                 if [ -z "$pid" ] ; then
                     log_daemon_msg "unknow error, check /var/log" "$NAME"
		     log_end_msg 1
                 else
                     echo "$pid" > "$PIDFILE"
		     log_end_msg $status
                 fi
	;;
  stop)
	log_daemon_msg "Stopping ALL the $DESC instances" "$NAME"
                 pid="$(pidof iperf3)"
                 if [ -z "$pid" ] ; then
                     log_daemon_msg "PID file empty" "$NAME"
                     log_end_msg 1
                     exit 1
                 fi
                 kill -2 "$pid"
                 log_end_msg $?
                 rm -f $PIDFILE
                 exit 0
	;;
  status)
	status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
	;;
  *)
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|status}" >&2
	exit 3
	;;
esac

exit 0
