#!/usr/bin/sh

function startbasicdsd
{
   startdaemon=false
   pids=$(ps -e | awk '$NF~/^basicdsd/ {print $1}')

   if [[ "$pids" = "" ]]
   then
      startdaemon=true

   elif [[ "$1" = "restart" ]]
   then
      for pid in $pids
      do
         if kill "$pid"; then
            print "Stopped basicdsd (pid ${pid})."
         fi
      done

      typeset -i n=1

      while pids=$(ps -e | awk '$NF~/^basicdsd/ {print $1}')
            [[ "$pids" != "" && "$n" -lt 10 ]]
      do
         sleep 1
         (( n = n + 1 ))
      done

      startdaemon=true
   fi

   if [[ $startdaemon = true ]]
   then
      basicdsd &
      pids=$(ps -e | awk '$NF~/^basicdsd/ {print $1}')
      typeset -i n=1

      for pid in $pids
      do
         if [[ "$n" -eq 1 ]]
         then
            print "Started basicdsd (pid ${pid})."
         else
            if kill "$pid" > /dev/null 2>&1 ; then
               print "Stopped duplicate basicdsd (pid ${pid})."
            fi
         fi

         (( n = n + 1 ))
      done

      return 0
   fi

   return 1
}

startbasicdsd $1
