#!/bin/sh

. /etc/control.d/functions-local-policy

CONFIG_COMMON=/etc/pam.d/system-auth-common
CONFIG_SYSTEM=/etc/pam.d/system-auth

if [ -f "$CONFIG_COMMON" ]; then
	CONFIG="$CONFIG_COMMON"
else
	CONFIG="$(readlink -e "$CONFIG_SYSTEM")" ||
	CONFIG="$CONFIG_SYSTEM"
fi

REQUEST="$*"

new_summary "pam_propperpwnam support in system authentication"

new_subst enabled \
        '^\s*(auth)\s+(optional|required)\s+pam_propperpwnam\.so(\s*|\s+.*)$' \
        's,^[[:space:]#]*#\(\s*\(auth\)\s\+\(optional\|required\)\s\+pam_propperpwnam\.so\(\s*\|\s\+.*\)\)$,\1,'
new_subst disabled \
        '^[[:space:]#]*#\s*(auth)\s+(optional|required)\s+pam_propperpwnam\.so(\s*|\s+.*)$' \
        's,^\(\s*\(auth\)\s\+\(optional\|required\)\s\+pam_propperpwnam\.so\(\s*\|\s\+.*\)\)$,#\1,'

if is_file_exists "$CONFIG" && ! is_builtin_mode "$REQUEST"; then
	case "$REQUEST" in
	enabled|disabled)
		if ! grep -Eq '^[[:space:]#]*auth\s+(optional|required)\s+pam_propperpwnam\.so(\s*|\s+.*)$' "$CONFIG"; then
			if [ "$CONFIG" != "$CONFIG_COMMON" ]; then
				echo_error "Custom configuration file '$CONFIG' not contains: 'auth optional pam_propperpwnam.so'"
				exit 4
			fi
			sed -i --follow-symlinks -e 's/^\(\s*#%PAM-.*\)/\1\n#auth\t\toptional\tpam_propperpwnam.so/' -- "$CONFIG" || exit 3
		fi
		;;
	esac
fi

new_help enabled "Enable pam_propperpwnam support"
new_help disabled "Disable pam_propperpwnam support"

control_subst_with_file_check "$CONFIG" "$REQUEST" "enabled disabled"
