#!/bin/sh

<% if attributes[:deb_maintainerscripts_force_errorchecks?] -%>
set -e
<% end -%>

after_upgrade() {
<%# Making sure that at least one command is in the function -%>
<%# avoids a lot of potential errors, including the case that -%>
<%# the script is non-empty, but just whitespace and/or comments -%>
    :
<% if script?(:after_upgrade) -%>
<%=  script(:after_upgrade) %>
<% end -%>

<%# if any systemd services specified, loop through and start them -%>
<% if attributes[:deb_systemd].any? -%>
systemctl --system daemon-reload >/dev/null || true
debsystemctl=$(command -v deb-systemd-invoke || echo systemctl)
<% attributes[:deb_systemd].each do |service| -%>
if ! systemctl is-enabled <%= service %> >/dev/null 
then
  : # Ensure this if-clause is not empty. If it were empty, and we had an 'else', then it is an error in shell syntax
<% if attributes[:deb_systemd_enable?]-%>
    systemctl enable <%= service %> >/dev/null || true
<% end -%>
<% if attributes[:deb_systemd_auto_start?]-%>
    $debsystemctl start <%= service %> >/dev/null || true
<% end -%>
<% if attributes[:deb_systemd_restart_after_upgrade?] -%>
else
    $debsystemctl restart <%= service %> >/dev/null || true
<% end -%>
fi
<% end -%>
<% end -%>
}

after_install() {
<%# Making sure that at least one command is in the function -%>
<%# avoids a lot of potential errors, including the case that -%>
<%# the script is non-empty, but just whitespace and/or comments -%>
    :
<% if script?(:after_install) -%>
<%=  script(:after_install) %>
<% end -%>

<%# if any systemd services specified, loop through and start them -%>
<% if attributes[:deb_systemd].any? -%>
systemctl --system daemon-reload >/dev/null || true
debsystemctl=$(command -v deb-systemd-invoke || echo systemctl)
<% attributes[:deb_systemd].each do |service| -%>
<% if attributes[:deb_systemd_enable?]-%>
systemctl enable <%= service %> >/dev/null || true
<% end -%>
<% if attributes[:deb_systemd_auto_start?]-%>
$debsystemctl start <%= service %> >/dev/null || true
<% end -%>
<% end -%>
<% end -%>
}

if [ "${1}" = "configure" -a -z "${2}" ] || \
   [ "${1}" = "abort-remove" ]
then
    # "after install" here
    # "abort-remove" happens when the pre-removal script failed.
    #   In that case, this script, which should be idemptoent, is run
    #   to ensure a clean roll-back of the removal.
    after_install
elif [ "${1}" = "configure" -a -n "${2}" ]
then
    upgradeFromVersion="${2}"
    # "after upgrade" here
    # NOTE: This slot is also used when deb packages are removed,
    # but their config files aren't, but a newer version of the
    # package is installed later, called "Config-Files" state.
    # basically, that still looks a _lot_ like an upgrade to me.
    after_upgrade "${2}"
elif echo "${1}" | grep -E -q "(abort|fail)"
then
    echo "Failed to install before the post-installation script was run." >&2
    exit 1
fi
