#!/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"

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

    if [ -z "$2" ]; then
        log "First installation detected..."
        # first install: setup the recommended configuration (unless
        # nsswitch.conf already contains authd entries)
        insert_nss_entry
    fi
fi
