#!/bin/sh
# postrm script for memgraph
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postrm> `remove'
#        * <postrm> `purge'
#        * <old-postrm> `upgrade' <new-version>
#        * <new-postrm> `failed-upgrade' <old-version>
#        * <new-postrm> `abort-install'
#        * <new-postrm> `abort-install' <old-version>
#        * <new-postrm> `abort-upgrade' <old-version>
#        * <disappearer's-postrm> `disappear' <overwriter>
#          <overwriter-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package

var_files="/var/lib/memgraph /var/log/memgraph"

case "$1" in
    purge)
        # Remove 'var/*/memgraph' directories, even if they contain something.
        for var_file in $var_files; do
            rm -rf $var_file
        done
        # Remove generated SSL certificates
        if [ -d /etc/memgraph/ssl ]; then
            rm -rf /etc/memgraph/ssl
        fi
        # Don't remove the 'memgraph' user, since we cannot be sure whether it
        # existed before.
    ;;

    remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
        # Default behaviour does what we expect, removes untouched installed
        # files but keeps configuration.
    ;;

    *)
        echo "postrm called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# Remove and purge systemd memgraph.service. The following was autogenerated
# by dh_systemd_enable and dh_systemd_start.

if [ -d /run/systemd/system ]; then
    systemctl --system daemon-reload >/dev/null || true
fi

if [ "$1" = "remove" ]; then
    if [ -x "/usr/bin/deb-systemd-helper" ]; then
        deb-systemd-helper mask memgraph.service >/dev/null
    fi
fi

if [ "$1" = "purge" ]; then
    if [ -x "/usr/bin/deb-systemd-helper" ]; then
        deb-systemd-helper purge memgraph.service >/dev/null
        deb-systemd-helper unmask memgraph.service >/dev/null
    fi
fi

# Remove the libpython3.so symlink created in postinst, but only on actual
# removal/purge (not upgrade, where the replacement still needs it) and only if
# it is still a symlink pointing at a versioned libpython (i.e. one we created,
# not a file owned by another package such as libpython3-dev).
if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then
    removed_symlink=false
    for link in /usr/lib/*/libpython3.so /usr/lib64/libpython3.so /usr/lib/libpython3.so; do
        if [ -L "$link" ]; then
            case "$(readlink "$link")" in
                libpython3.*.so.1.0)
                    rm -f "$link"
                    removed_symlink=true
                ;;
            esac
        fi
    done
    if [ "$removed_symlink" = true ]; then
        ldconfig || true
    fi
fi

# Take a look at the preinst script for the detailed explanation.
if dpkg-maintscript-helper supports rm_conffile 2>/dev/null; then
    dpkg-maintscript-helper rm_conffile /etc/logrotate.d/memgraph_audit 1.1.999 -- "$@"
fi

exit 0
