#!/bin/ksh
#
# svscan - starts and monitors a collection of services
#
# chkconfig: 2345 00 99
# chkconfig.solaris: 2 00 99
# chkconfig.aix: 2 200 99
# chkconfig.debian: 2345 05 95
# description: svscan starts one supervise process for service directories
# processname: svscan

. /opt/osstech/etc/sv/svfunc || exit 1

sv_title="daemontools svscan"
sv_initname=`echo "${0##*/}" |sed 's/^[._]*[SK]*[0-9]*//'`
sv_cmd_basename="svscan"
sv_cmd="/opt/osstech/bin/svscan"
sv_cmd_boot="/opt/osstech/bin/svscanboot"
sv_default_file="/opt/osstech/etc/default/svscan"

[ -x "$sv_cmd" ] || exit 1
[ -x "$sv_cmd_boot" ] || exit 1

[ -f "$sv_default_file" ] && . "$sv_default_file"

function sv_start {
  echo_n "Starting $sv_title: "
  if sv_status >/dev/null 2>&1; then
    failure; echo
    return 1
  fi
  /usr/bin/nohup "$sv_cmd_boot" >/dev/null 2>&1 </dev/null &
  typeset pid="$!"
  /bin/sleep 1
  if kill -0 "$pid" 2>/dev/null; then
    : OK
  else
    failure; echo
    return 1
  fi

  success; echo
  [ -d /var/lock/subsys ] && touch "/var/lock/subsys/$sv_initname"
  return 0
}

function sv_stop {
  echo_n "Stopping $sv_title: "
  if sv_status >/dev/null 2>&1; then
    : OK
  else
    failure; echo
    return 1
  fi
  if killproc "$sv_cmd_basename"; then
    : OK
  else
    failure; echo
    return 1
  fi

  success; echo
  [ -d /var/lock/subsys ] && rm -f "/var/lock/subsys/$sv_initname"

  typeset i
  for i in /opt/osstech/etc/svscan/*; do
    test -x "$i/run" && /opt/osstech/bin/svc -dx "$i"
    test -d "$i/log" -a -x "$i/log/run" && /opt/osstech/bin/svc -dx "$i/log"
  done

  return 0
}

function sv_status {
  status "$sv_cmd_basename"
}

function sv_init {
  case "$1" in
  start)
    sv_start
    return $?
    ;;
  stop)
    sv_stop
    return $?
    ;;
  status)
    sv_status
    return $?
    ;;
  restart)
    sv_stop
    sv_start
    return $?
    ;;
  condrestart)
    sv_status >/dev/null 2>&1 || return 0
    sv_stop
    sv_start
    return $?
    ;;
  *)
    echo "Usage: $sv_argv0 {start|stop|status|restart|condrestart}"
    return 1
    ;;
  esac
}

sv_init ${1+"$@"}

