#!/bin/bash
#
# Perform any required volatile run-time initialization

set -eu -o pipefail
shopt -s inherit_errexit
if [ "${DEBUG:=false}" = "true" ]
then
    # Echo commands for easier debugging
    set -x
    PS4='$0:$LINENO+'
fi


main() {
    if [ -n "${PUID:-}" ]
    then
	if (( $(id -u) != 0 ))
	then
	    set +x
	    echo "ERROR: Can't create a user when not run as root" 1>&2
	    false
	fi
	if ! id "${PUID}" >"/dev/null" 2>&1
	then
	    # Add a user to the `passwd` DB so that the `~python-project-structure/`
	    # HOME directory can be looked up.
	    adduser --uid "${PUID}" --disabled-password --gecos \
		    "Python Project Structure,,," "python-project-structure" \
		    >"/dev/null"
	fi
	# Fix the TTY ownership if the session is interactive
	if tty_dev=$(tty)
	then
	    chown "${PUID}" "${tty_dev}"
	fi
	# Delegate the rest to the `CMD`
	exec gosu "${PUID}:${PGID:-${PUID}}" "${@}"
    fi

    # Delegate the rest to the `CMD`
    exec "$@"
}

main "$@"
