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

fatal() {
  echo "svc-remove: 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-remove $@" >&2
    exit 1
  fi
}

usage $# 1 1 service

svc="$1"

svc-stop -q "$svc"

if ! [ -L "$svc" ]; then
  fatal "Service '$svc' is not symlinked into /service and can't be removed."
fi

# Remove the symlink without loosing track of where it points to
cd "$svc"
rm ${SVSCANDIR-/service}/"$svc"

# Stop the supervise tasks
if [ -d log ]; then
  svc -dx log
fi
svc -dx .
