#!/bin/sh
#
# svinitd
# init.d wrapper for daemontools services
# Klaus Reimer <k@ailis.de>

if [ "$INIT_VERSION" != "" ]
then
  exit 0
fi

TITLE=svinitd
VERSION=0.3
AUTHOR="Klaus Reimer"
EMAIL=k@ailis.de
COPYRIGHT="Copyright (C) 2000-2003 by $AUTHOR"

showHelp() {
  echo "Usage: $TITLE [OPTION]... SERVICE CMD"
  echo "init.d wrapper for daemontools services"
  echo ""
  echo "  -h, --help     Display help and exit"
  echo "  -V, --version  Display version and exit"
  echo ""
  echo "This utility is an init.d wrapper. You can use this tool"
  echo "to translate init.d commands (like stop, start, restart...) to svc"
  echo "commands. This tool is intended to be used in an init.d script."
  echo ""
  echo "Report bugs to $AUTHOR <$EMAIL>"
}

showVersion() {
  echo "$TITLE $VERSION"
  echo ""
  echo "$COPYRIGHT"
  echo "This is free software; you can redistribute it and/or modify it under"
  echo "the terms of the GNU General Public License as published by the Free"
  echo "Software Foundation; either version 2 of the License, or (at your"
  echo "option) any later version."
}

while getopts "hV-:" NAME
do
  case "$NAME" in
    h)
      showHelp
      exit 0
      ;;
    V)
      showVersion
      exit 0
      ;;
    -)
      case "$OPTARG" in
        help)
          showHelp
          exit 0
          ;;
        version)
          showVersion
          exit 0
          ;;
        *)
          echo "Unknown option: $OPTARG"
          showHelp
          exit 1
      esac  
      ;;
    *)
      echo "Unknown option: $OPTARG"
      showHelp
      exit 1
  esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 2 ]
then
  showHelp
  exit 1
fi

if ! SVDIR=`svdir 2>&1`
then
  echo "$TITLE: $SVDIR" >&2
  exit 1
fi

SERVICE=$1

svok $SVDIR/$SERVICE || exit 1

COMMAND=$2

case "$COMMAND" in
  start)
    echo -n "Starting supervised $SERVICE... "
    svc -u $SVDIR/$SERVICE
    echo "Done"
    ;;
  stop)
    echo -n "Stopping supervised $SERVICE... "
    svc -d $SVDIR/$SERVICE
    echo "Done"
    ;;
  reload)
    echo -n "Reloading supervised $SERVICE... "
    svc -h $SVDIR/$SERVICE
    echo "Done"
    ;;
  restart)
    echo -n "Restarting supervised $SERVICE... "
    svc -t $SVDIR/$SERVICE
    echo "Done"
    ;;
  force-reload)
    echo -n "Force-reloading supervised $SERVICE... "
    svc -k $SVDIR/$SERVICE
    echo "Done"
    ;;
  enable)
    echo -n "Enabling supervised $SERVICE... "
    rm -f $SVDIR/$SERVICE/down
    echo "Done"
    ;;
  disable)
    echo -n "Disabling supervised $SERVICE... "
    touch $SVDIR/$SERVICE/down
    echo "Done"
    ;;
  *)
    echo "$0($SERVICE) {start|stop|reload|restart|force-reload|enable|disable}"
    exit 1
    ;;
esac

exit 0
