#!/bin/sh

### BEGIN INIT INFO
# Provides:          sftd
# X-Start-Before:    ssh
# Required-Start:    $local_fs $network $named $syslog
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ScaleFT daemon
# Description:       Enable ScaleFT management of this server.
### END INIT INFO

NAME="ScaleFT server daemon"
DAEMON="/usr/sbin/sftd"
PID_FILE="/var/run/sftd.pid"
OUT_FILE="/var/log/sftd.log"
PATH="${PATH}:/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin"

get_pid() {
  cat "${PID_FILE}"
}

is_running() {
  [ -f "${PID_FILE}" ] && ps $(get_pid) 2>&1 > /dev/null
}

start_daemon() {
  if is_running; then
    echo "Already started"
    exit 1
  fi
  echo "Starting ${NAME}..."
  ${DAEMON} 0<&- > ${OUT_FILE} 2>&1 &
  echo ${!} > ${PID_FILE}
  echo "Done"
}

stop_daemon() {
  if ! is_running; then
    echo "Not running"
    exit 7
  fi
  echo "Stopping ${NAME}..."
  kill $(get_pid)
  ret=${?}
  if [ ${ret} -eq 0 ]; then
    rm -f ${PID_FILE}
    echo "Stopped"
  else
    echo "Failed to stop"
    exit 1
  fi
}

restart_daemon() {
  if is_running; then
    stop_daemon
  fi
  start_daemon
}

daemon_status() {
  if is_running; then
    echo "Running"
  else
    echo "Stopped"
    exit 3
  fi
}

case "${1}" in
  start)
    shift
    start_daemon
    ;;
  stop)
    stop_daemon
    ;;
  restart)
    restart_daemon
    ;;
  status)
    daemon_status
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac
