#!/bin/sh
# WARNING: This file was auto-generated. Do not edit!
echon() {
  echo -n "$*"
}
set -e
PATH="/bin:/usr/bin:/usr/local/bin:$PATH"
export PATH
program=`basename $0`

warn() {
  echo "$program: Warning: $@" >&2
}

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

usage_nocd() {
  min=$1; max=$2; opts=$3; msg=$4; shift 4

  while getopts q$opts flag; do
    case $flag in
      q)
        exec >/dev/null
	;;
      \? | :)
        exit 1
	;;
      ?)
        eval "opt_${flag}=true"
	;;
    esac
  done

  shift=$(( $OPTIND - 1 ))
  shift $shift

  if [ $# -lt $min -o $# -gt $max ]; then
    echo "$0: usage: $program [-q] $msg" >&2
    exit 1
  fi
}

usage() {
  usage_nocd "$@"
  cd "$SVSCANDIR"
}

SVSCANDIR="${SVSCANDIR-/service}"
SVCLOCKDIR="${SVCLOCKDIR-/var/service}"
opt_k=false
usage 1 9999 'k' "[-k] service [service ...]" "$@"
shift $(( $OPTIND - 1 ))

stopandwait() {
  if svc-isup "$1"; then
    svc $2 "$1"
    svc-waitdown "$1" && echon "$1 "
  else
    echon "$1 (already down) "
  fi
}

stop() {
  touch "$1"/down
  if stopandwait "$1" -d; then
    return
  fi
  if $opt_k; then
    echon " Failed to stop, killing: "
    if stopandwait "$1" -k; then
      return
    fi
  fi
  fatal "Failed to stop '$1'."
}

for svc in "$@"; do

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

  echon "Stopping $svc: "

  stop "$svc"

  if [ -d "$svc/log" ]; then
    stop "$svc/log"
  fi

  echo "done."

done
