#!/bin/bash -e

SUPATH='/usr/sbin'

if getent passwd "$PAM_USER" >/dev/null 2>&1; then
    # Terminate the PAM authentication stack. The SSH client will fail since the user didn't supply a valid public key.
    exit $PAM_SUCCESS
else
    # Create the user, then terminate the PAM authentication stack. The SSH client will fail, and the user will need to try again.
    # TODO: figure out how to display info banner
    # Verify that the IAM user exists.
    if ! keymaker get_authorized_keys "$PAM_USER" >/dev/null 2>&1; then
      exit $PAM_SUCCESS
    fi
    NEW_UID=$(keymaker get_uid "$PAM_USER")
    if ! [ $(command -v useradd > /dev/null) ]; then
        ${SUPATH}/useradd "$PAM_USER" --comment "$PAM_USER" --uid "$NEW_UID" --shell "/bin/bash" --create-home
    else
        ${SUPATH}/adduser "$PAM_USER" --disabled-password --gecos "$PAM_USER" --uid "$NEW_UID" --shell "/bin/bash" --create-home
    fi
    for group in $(keymaker get_groups "$PAM_USER"); do
        ${SUPATH}/usermod --append --groups "$group" "$PAM_USER" || echo "$0: Error while adding user to group"
    done
    echo "Keymaker: Your user account has been replicated to this host but cannot be used for this session."
    echo "Keymaker: Create a new SSH connection."
    exit $PAM_SUCCESS
fi
