#!/usr/bin/env bash

# {{ ansible_managed }}

# Clean up 'debops.nullmailer' modifications on the 'nullmailer' package purge

set -o nounset -o pipefail -o errexit

readarray -t purge_files << EOF
{% for element in (nullmailer__configuration_files + nullmailer__private_configuration_files + nullmailer__purge_default_files + nullmailer__purge_files) %}
{%   if element is mapping %}
{%     if (element.purge is undefined or element.purge|bool) %}
{{ element.dest }}
{%     endif %}
{%   elif element is string %}
{{ element }}
{%   else %}
{%     for entry in element %}
{{ entry }}
{%     endfor %}
{%   endif %}
{% endfor %}
EOF

debops_nullmailer_file_cleanup () {

    printf "Purging nullmailer configuration maintained by Ansible ...\\n"
    for purge_file in "${purge_files[@]}" ; do
        test ! -f "${purge_file}" || rm -f "${purge_file}"
    done
}

debops_nullmailer_xinetd_cleanup () {

    if [ -d /etc/xinetd.d ] && [ -f /etc/xinetd.d/nullmailer-smtpd ] ; then

        test ! -f /etc/xinetd.d/nullmailer-smtpd || rm -f /etc/xinetd.d/nullmailer-smtpd

        if pidof systemd > /dev/null 2>&1 ; then

            xinetd_state="$(systemctl is-active xinetd.service)"
            if [ "${xinetd_state}" = "active" ] ; then
                systemctl reload xinetd.service
            fi

        else

            xinetd_pidfile="/run/xinetd.pid"
            if [ -f "${xinetd_pidfile}" ] ; then
                if kill -0 "$(<"${xinetd_pidfile}")" > /dev/null 2>&1 ; then
                    /usr/sbin/service xinetd reload > /dev/null
                fi
            fi

        fi
    fi

}


dpkg_pid="$(ps -o ppid= ${PPID} | tr -d '[:space:]')"

IFS=' ' read -r -a arguments <<< "$(tr '\0' ' ' < "/proc/${dpkg_pid}/cmdline")"

if [ -n "${DPKG_HOOK_ACTION:-}" ] ; then
    case ${DPKG_HOOK_ACTION} in
        remove)
            for x in "${arguments[@]}"; do
                case ${x} in
                    nullmailer:*)
                        debops_nullmailer_xinetd_cleanup
                    ;;
                esac
            done
        ;;
        purge)
            for x in "${arguments[@]}"; do
                case ${x} in
                    nullmailer:*)
                        debops_nullmailer_xinetd_cleanup
                        debops_nullmailer_file_cleanup
                    ;;
                esac
            done
        ;;
    esac
fi
