#!/bin/bash

help() {
  >&2 echo '
s6 compatibility script of:

/usr/bin/deb-systemd-helper is a program which should be called by dpkg maintscripts only. Please do not run it interactively, ever.
'
}

# discard all option parameters
while [[ $1 =~ ^- ]]; do
  if [ "$1" = '--help' ] || [ "$1" = '-h' ]; then
    help
    exit 0
  fi
  shift
done

# need at least 2 non-option arguments (service name and action)
if [ $# -lt 2 ]; then
  help
  exit 1
fi

# update databases, so we can check if service name exists
svctl compile && svctl update

# only manage service if it's known to s6
svc=${2%.service}
if svctl listall | grep -q "^$svc$"; then
  case "$1" in
    disable|purge)
      svctl disable "$svc" || exit 1
      ;;
    enable)
      svctl enable "$svc" || exit 1
      ;;
  esac
else
  echo "Service ${svc} is unknown to s6."
fi

# make changes persistent
svctl compile && svctl update

exit 0
