#!/bin/sh
set -e
PATH="$PATH:/usr/local/bin"
export PATH
cd "${SVSCANDIR-/service}"

fatal() {
  echo "svc-start: Fatal error: $@" >&2
  exit 1
}

usage() {
  args=$1; min=$2; max=$3; shift 3
  if [ $args -lt $min -o $args -gt $max ]; then
    echo "$0: usage: svc-start $@" >&2
    exit 1
  fi
}

if [ "$1" = -q ]; then
  exec >/dev/null
  shift
fi

usage $# 1 1 "[-q] service"

svc="$1"

if ! [ -e "$svc" ]; then
  fatal "Service '$svc' does not exist."
fi

start() {
  # Check the "run" file
  if [ ! -e "$1/run" ]; then
    fatal "'$1/run' file does not exist!"
  fi

  rm -f "$1/down"

  if ! svok "$1"; then
    echo -n "(supervise"
    count=1
    until svok "$1"; do
      echo -n .
      sleep 1
      let count=count+1
      if [ $count -gt ${SVCTIMEOUT-15} ]; then
        echo -n ") "
	fatal "supervise for '$1' did not start!"
      fi
    done
    echo -n ") "
  fi

  svc -u "$1"
  svc-waitup "$1"

  echo -n "$1 "
}

echo -n "Starting $svc: "

# Control the log process first, so that all messages are logged ...
if [ -k "$svc" ]; then
  start "$svc/log"
fi

# ... and then the main process.
start "$svc"

echo "done."
