#!/bin/sh

function usage() {
  echo ""
  echo "Usage: service [-h] <service-name> <action>"
  echo ""
  echo "Switches: -h   Help"
  echo ""
  echo "Actions: start, stop, restart"
  echo ""
  echo -n "Services: "

  for service in $services; do
    last_service=$service
  done

  service_count=0
  for service in $services; do
    let service_count=service_count+1
    if [ "$service" = "$last_service" ]; then
      echo "$service"
    else
      echo -n "$service, "
      let service_in_row=service_count%5
      [ $service_in_row = 0 ] && echo
    fi
  done
  echo
}

actions="start stop restart"
services=`ls /etc/rc.d`

if [ "$1" = "" ] || [ "$1" = "-h" ]; then
  usage
  exit 1
fi

if [ ! "$3" = "" ]; then
  echo
  echo "Too many arguments!"
  echo
  echo "Use -h to help"
  exit 1
fi

service_supported=0
for service in $services; do
  if [ "$service" = "$1" ]; then
    service_supported=1
    break
  fi
done

if [ $service_supported = 0 ]; then
  echo
  echo "Unsupported service!"
  echo
  echo "Use -h to help"
  exit 1
fi

action_supported=0
for action in $actions; do
  if [ "$action" = "$2" ]; then
    action_supported=1
    break
  fi
done

if [ $action_supported = 0 ]; then
  echo
  echo "Unsupported action!"
  echo
  echo "Use -h to help"
  exit 1
fi

/etc/rc.d/$1 $2