#!/bin/sh
# prerm script for yandex-cauth
#
# see: dh_installdeb(1)

#set -e

# summary of how this script can be called:
#        * <prerm> `remove'
#        * <old-prerm> `upgrade' <new-version>
#        * <new-prerm> `failed-upgrade' <old-version>
#        * <conflictor's-prerm> `remove' `in-favour' <package> <new-version>
#        * <deconfigured's-prerm> `deconfigure' `in-favour'
#          <package-being-installed> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package


case "$1" in
    remove)
        # revert pam configs
        pam-auth-update --remove cauth --force

        # disable ssh keys resolving
        sed -i -e '/^AuthorizedKeysCommand .*$/d' /etc/ssh/sshd_config
        sed -i -e '/^AuthorizedKeysCommandUser .*$/d' /etc/ssh/sshd_config
        systemctl reload ssh
        systemctl restart dbus
         # unfortunately cqudp uses nsswitch.conf and requires restart to use new nss module
        for i in $(pgrep cqudp)
        do
            # restart only dom0 cqudp instance
            grep -q 'pids:/$' /proc/$i/cgroup && kill -9 $i
        done

        # do a bit harmful portod reload (causes porto requests failure for a short period)
        if [ ! -z "$(pgrep portod)" ]
        then
            portod reload
        fi

        # revert nsswitch
        mv /etc/nsswitch.conf.userd-backup /etc/nsswitch.conf

        if [ -z $HOSTMAN ]
        then
            systemctl disable yandex-cauth-userd.socket
            systemctl stop yandex-cauth-userd.socket

            systemctl disable yandex-cauth-userd.service
            systemctl stop yandex-cauth-userd.service
        fi
    ;;

    upgrade|deconfigure|failed-upgrade)
    ;;

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

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
