#!/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
    adduser "$PAM_USER" --disabled-password --gecos "$PAM_USER" --uid "$(keymaker get_uid '$PAM_USER')"
    echo "$0: Your user account has been created on demand, but SSH will not know about it until you reconnect." > /dev/stderr
    echo "$0: Connect with SSH again to log in to your account." > /dev/stderr
    exit $EX_TEMPFAIL
fi
