#!/bin/bash -e

EX_TEMPFAIL=75
EX_NOPERM=77

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 $EX_NOPERM
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.
    keymaker get_authorized_keys "$PAM_USER" >/dev/null
    NEW_UID=$(keymaker get_uid "$PAM_USER")
    adduser "$PAM_USER" --disabled-password --gecos "$PAM_USER" --uid "$NEW_UID"
    for group in $(keymaker get_groups "$PAM_USER"); do
        usermod --append --groups "$group" "$PAM_USER" || echo "$0: Error while adding user to group"
    done
    echo "Keymaker: Your user account has been replicated onto this host, but SSH will not recognize it until you reconnect."
    echo "Keymaker: Connect again to log in to your account."
    exit $EX_TEMPFAIL
fi
