#!/bin/sh
set -e

#DEBHELPER#

# This code was taken from libnss-sss, which got it from libnss-myhostname, which got it from nss-mdns:

log() {
    echo "$*"
}

# try to insert authd entries to the passwd, group and shadow
# lines in /etc/nsswitch.conf to automatically enable libnss-authd
# support; do not change the configuration if the lines already
# reference some authd lookups
insert_nss_entry() {
    log "Checking NSS setup..."
    # abort if /etc/nsswitch.conf does not exist
    if ! [ -e /etc/nsswitch.conf ]; then
        log "Could not find /etc/nsswitch.conf."
        return
    fi
    # append 'authd' to the end of the line if it's not found already
    sed -i --regexp-extended '
      /^(passwd|group|shadow):/ {
        /\bauthd\b/! s/$/ authd/
      }
    ' /etc/nsswitch.conf
}

action="$1"
previous_version="$2"

if [ configure = "$action" ]; then
    pam-auth-update --package
    insert_nss_entry

    # We installed /etc/authd with permissions 777 - umask in versions prior to 0.4.0
    if dpkg --compare-versions "$previous_version" lt-nl "0.4.0~"; then
        # Ensure that the /etc/authd directory has mode 700
        if [ -d /etc/authd ] && [ "$(stat -c %a /etc/authd)" != "700" ]; then
            chmod 700 /etc/authd
        fi
    fi

    # Version 0.5.0 introduced breaking changes to the API, which requires a reboot
    # to avoid issues between gnome-shell and authd.
    if dpkg --compare-versions "$previous_version" lt-nl "0.5.0~" && \
       command -v /usr/share/update-notifier/notify-reboot-required >/dev/null; then
            /usr/share/update-notifier/notify-reboot-required
    fi
fi
