#!/bin/sh

. /etc/control.d/functions

CONFIG="${CONFIG:-/etc/pam.d/system-auth}"

# Resolve the links because sed -i replaces the files
CONFIG="$(realpath "$CONFIG")"

new_summary "pam_mkuser switch"
new_help 'enabled' "Accounts for unknown users are created on login"
new_help 'disabled' "No new accounts are created for unknown users"

check_enabled() {
    [ -e "$CONFIG" ] || return 1
    sed -n -e '/^account[[:space:]]\+optional[[:space:]]\+pam_mkuser\.so\([[:space:]].*\)\?$/ { q 0 }' \
           -e '/^account[[:space:]]/ { q 1 }' \
        "$CONFIG"
}

enable_mkuser() {
    sed -i -e '/^#[[:space:]]*account[[:space:]]\+optional[[:space:]]\+pam_mkuser\.so\([[:space:]].*\)\?$/ {
                  s/^[[:space:]]*#//;
                  :exit0 n; b exit0;
               }' \
           -e '/^account[[:space:]]\+optional[[:space:]]\+pam_mkuser\.so\([[:space:]].*\)\?$/ { :exit1 n; b exit1; }' \
           -e '/^account[[:space:]]/ {
                  s/^.*$/account\t\toptional\tpam_mkuser\.so shell=\/bin\/bash debug\n&/;
                  :exit2 n; b exit2;
               }' \
        "$CONFIG"
}

disable_mkuser() {
    sed -i -e 's/^account[[:space:]]\+optional[[:space:]]\+pam_mkuser\.so\([[:space:]].*\)\?$/#&/' "$CONFIG"
}

## Main

REQUEST="$*"

case "$REQUEST" in
	help|'help '*)
		control_help "${REQUEST#help}"
		;;
	list)
		control_list
		;;
	summary)
		control_summary
		;;
	status)
		if check_enabled; then
            echo 'enabled'
        else
            echo 'disabled'
        fi
		;;
	enabled)
		enable_mkuser
		;;
    disabled)
        disable_mkuser
        ;;
esac
