#!/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)
      # 0.1.11: NO svctl enable any more. "Packages yes, services off, Puppet
      # switches on": dh_installinit/dh_installsystemd call this on EVERY
      # upgrade, and until 0.1.10 it re-enabled even a service that had been
      # switched off on purpose (Debian does not: defaults is a no-op once
      # links exist, and deb-systemd-helper honours was-enabled). Measured on
      # 23.09.2026 on infra-1.tick1: upgrading retain 0.16.6->0.16.7 enabled
      # retain, and the following invoke-rc.d restart started it together with
      # lxe. Enabling at FIRST installation is done by dh-s6 itself (marker,
      # .noenable) -- this path is not needed. Inventory before the build:
      # every service that should run and was enabled here so far has a
      # Puppet entry with enable => true.
      >&2 echo "deb-systemd-helper: ${svc}: enable does not enable under s6 (policy). To enable: svctl enable ${svc} -- Puppet does that."
      ;;
  esac
else
  echo "Service ${svc} is unknown to s6."
fi

# make changes persistent
svctl compile && svctl update

exit 0
