#!/bin/bash -ex

################################################################################
#
# MIT License
#
# Copyright 2019-2025 AMD ROCm(TM) Software
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell cop-
# ies of the Software, and to permit persons to whom the Software is furnished
# to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM-
# PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNE-
# CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################


chgrp tty /dev/tty*

if id "${_USER}" &>/dev/null; then
    echo "${_USER} already exists, skipping creation."
else
    echo "Creating user ${_USER}."
    useradd -o -m ${_USER} --uid ${_UID} --gid tty --gid video -s /bin/bash
    mkhomedir_helper ${_USER}

    echo "$_USER    ALL=(ALL:ALL) NOPASSWD: ALL" >> /etc/sudoers
fi

if getent group render &>/dev/null; then
    echo "render already exists, skipping creation."
elif [[ -z "${_RENDER_GID}" ]]; then
    echo "RENDER GID not passed in, skipping config."
else
    echo "Configuring render group."
    sudo groupadd --gid ${_RENDER_GID} render
    sudo usermod -a -G render ${_USER}
fi

if [[ -z "${_GIT_EMAIL}" ]]; then
    echo "Git email not passed in, skipping config."
else
    echo "Configuring Git email."
    sudo su -l $_USER -c "git config --global user.email \"${_GIT_EMAIL}\""
fi

if [[ -z "${_GIT_USER}" ]]; then
    echo "Git name not passed in, skipping config."
else
    echo "Configuring Git username."
    sudo su -l $_USER -c "git config --global user.name \"${_GIT_USER}\""
fi

if [ -d "/data" ]; then
    cd /data
fi

if [ "$#" -gt 0 ]; then
    echo $#
    echo sudo -u $_USER "$@"
    exec su -l $_USER -c "$@"
else
    echo su --login $_USER
    su --login $_USER
fi
