#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2010-2016, OpenNebula Systems                                    #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

# defaults
USERNAME=${USERNAME:-root}
USERNAME_SHELL=${USERNAME_SHELL:-/bin/bash}
USERNAME_SUDO=${USERNAME_SUDO:-${GRANT_SUDO:-YES}}
USERNAME_SUDO=$(echo "${USERNAME_SUDO}" | tr '[:lower:]' '[:upper:]')
USERNAME_PASSWORD_RESET=${USERNAME_PASSWORD_RESET:-NO}
USERNAME_PASSWORD_RESET=$(echo "${USERNAME_PASSWORD_RESET}" | tr '[:lower:]' '[:upper:]')

if ! getent passwd "${USERNAME}" > /dev/null 2>&1; then
    useradd -m "${USERNAME}" -p '*' -s "${USERNAME_SHELL}"
fi

if [ "${USERNAME_SUDO}" == "YES" ] && [ "${USERNAME}" != "root" ]; then
    echo "${USERNAME} ALL=(ALL) NOPASSWD:ALL" >/etc/sudoers.d/one-context
    chmod 0440 /etc/sudoers.d/one-context
elif [ -f /etc/sudoers.d/one-context ]; then
    unlink /etc/sudoers.d/one-context
fi

if [ -n "${CRYPTED_PASSWORD_BASE64}" ]; then
    CRYPTED_PASSWORD=$(echo $CRYPTED_PASSWORD_BASE64 | base64 -d)
    usermod -p "${CRYPTED_PASSWORD}" "${USERNAME}"
elif [ -n "${PASSWORD_BASE64}" ]; then
    PASSWORD=$(echo $PASSWORD_BASE64 | base64 -d)
    chpasswd <<< "${USERNAME}:${PASSWORD}"

    if [ $? -ne 0 ]; then
        passwd "${USERNAME}" <<EOF
${PASSWORD}
${PASSWORD}
EOF
	fi
elif [ -n "${CRYPTED_PASSWORD}" ]; then
    usermod -p "${CRYPTED_PASSWORD}" "${USERNAME}"
elif [ -n "${PASSWORD}" ]; then
    chpasswd <<< "${USERNAME}:${PASSWORD}"

    if [ $? -ne 0 ]; then
        passwd "${USERNAME}" <<EOF
${PASSWORD}
${PASSWORD}
EOF
	fi
elif [ "${USERNAME_PASSWORD_RESET}" = 'YES' ]; then
    usermod -p '*' "${USERNAME}"
fi
