#! /bin/sh
# This script can be used to start/stop smsd
# as a daemon in Linux and Solaris.
# This script is an enhanced version of sms
# to be used with smsd version >= 3.0. 

# Maximum time to stop smsd, after that it gets killed hardly
maxwait=30
pidfile="/var/run/smsd.pid"
infofile="/var/run/smsd.working"
infofound=0
dots=0

case "$1" in
    start)
        if ps -e | grep smsd >/dev/null; then
          echo "Smsd is already running. Not starting the second smsd."
        else
          if [ -f $infofile ]; then
            rm $infofile
          fi
          find /var/spool/sms -name '*.LOCK' -exec rm {} \;
          /usr/local/bin/smsd &
        fi
        ;;
    stop)
        if ps -e | grep smsd >/dev/null; then
          kill `ps -e | grep smsd | awk '{print $1}'`
          sleep 1
          if ps -e | grep smsd >/dev/null; then
            echo "Allowing smsd to terminate gracefully within $maxwait seconds"
            seconds=0
            while ps -e | grep smsd >/dev/null; do
              if [ $infofound -lt 1 ]; then
                if [ -f $infofile ]; then
                  infofound=1
                  if [ $dots -gt 0 ]; then
                    echo ""
                    dots=0
                  fi
                  echo -n "Smsd is currently "
                  cat $infofile
                  echo "Time counting is now disabled and we will wait until this job is complete."
                  echo "If you are very hasty, use \"$0 force-stop\" to kill smsd hardly (not recommended)."
                fi
              fi
              if [ $infofound -lt 1 ]; then
                seconds=`expr $seconds + 1`
              fi
              echo -n "."
              dots=`expr $dots + 1`
              if [ "$seconds" -ge $maxwait ]; then
                if [ $dots -gt 0 ]; then
                  echo ""
                  dots=0
                fi
                echo "Timeout occured, killing smsd hardly."
                kill -9 `ps -e | grep smsd | awk '{print $1}'`
                if [ -f $pidfile ]; then
                  rm $pidfile
                fi
                seconds=0
              fi
              sleep 1
            done
            if [ $dots -gt 0 ]; then
              echo ""
            fi
            #echo "Smsd is stopped."
          fi
        fi
        ;;
    restart|reload)
        $0 stop
        $0 start
        ;;
    force-stop)
        if ps -e | grep smsd >/dev/null; then
          kill -9 `ps -e | grep smsd | awk '{print $1}'`
          if [ -f $pidfile ]; then
            rm $pidfile
          fi
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-stop}"
        exit 1
esac
