#!/bin/sh

set -eu

# Remove leftover files
find /tmp/ -mindepth 1 -delete ||:

# Add GPU devices groups to additional groups
for dev in /dev/dri/*; do
	[ -c "${dev:?}" ] || continue
	gid=$(stat -c '%g' "${dev:?}")
	uug=${UNPRIVILEGED_USER_GROUPS?}
	UNPRIVILEGED_USER_GROUPS="${uug:+${uug:?},}${gid:?}"
done

# Create additional groups
_IFS=${IFS}; IFS=,
for gid in ${UNPRIVILEGED_USER_GROUPS?}; do
	if ! getent group "${gid:?}" >/dev/null 2>&1; then
		groupadd --gid "${gid:?}" "g_${gid:?}"
	fi
done
IFS=$_IFS

# Create unprivileged user and group
if ! getent group "${UNPRIVILEGED_USER_GID:?}" >/dev/null 2>&1; then
	groupadd --gid "${UNPRIVILEGED_USER_GID:?}" "${UNPRIVILEGED_USER_NAME:?}"
fi
if ! getent passwd "${UNPRIVILEGED_USER_UID:?}" >/dev/null 2>&1; then
	useradd \
		--uid "${UNPRIVILEGED_USER_UID:?}" \
		--gid "${UNPRIVILEGED_USER_GID:?}" \
		--groups "${UNPRIVILEGED_USER_GROUPS?}" \
		--shell "${UNPRIVILEGED_USER_SHELL:?}" \
		--create-home \
		"${UNPRIVILEGED_USER_NAME:?}"
fi

# Set unprivileged user password
if [ -n "${UNPRIVILEGED_USER_PASSWORD?}" ]; then
	printf '%s' "${UNPRIVILEGED_USER_NAME:?}:${UNPRIVILEGED_USER_PASSWORD:?}" | chpasswd
else
	passwd -d "${UNPRIVILEGED_USER_NAME:?}"
fi

# Copy /etc/skel/ to unprivileged user home if empty
UNPRIVILEGED_USER_HOME=$(getent passwd "${UNPRIVILEGED_USER_NAME:?}" | cut -d: -f6)
if [ -z "$(ls -A "${UNPRIVILEGED_USER_HOME:?}")" ]; then
	cp -aT /etc/skel/ "${UNPRIVILEGED_USER_HOME:?}"
	chown -R "${UNPRIVILEGED_USER_NAME:?}:" "${UNPRIVILEGED_USER_HOME:?}"
fi

# Create /run/dbus/ directory if it does not exist
if [ ! -d /run/dbus/ ]; then
	mkdir -p /run/dbus/
	chmod 755 /run/dbus/
	chown messagebus: /run/dbus/
fi

# Create /run/sshd/ directory if it does not exist
if [ ! -d /run/sshd/ ]; then
	mkdir -p /run/sshd/
	chmod 755 /run/sshd/
fi

# Create /run/udev/ directory if it does not exist
if [ ! -d /run/udev/ ]; then
	mkdir -p /run/udev/
	chmod 755 /run/udev/
fi

# Create /run/user/${UNPRIVILEGED_USER_UID}/ directory if it does not exist
if [ ! -d /run/user/"${UNPRIVILEGED_USER_UID:?}"/ ]; then
	mkdir -p /run/user/"${UNPRIVILEGED_USER_UID:?}"/
	chmod 700 /run/user/"${UNPRIVILEGED_USER_UID:?}"/
	chown "${UNPRIVILEGED_USER_NAME:?}:" /run/user/"${UNPRIVILEGED_USER_UID:?}"/
fi

# Enable xdummy service if ENABLE_XDUMMY is true
if [ "${ENABLE_XDUMMY:?}" = 'true' ]; then
	ln -s /etc/sv/xdummy /etc/service/
fi

# Define VGL_DISPLAY variable if it is not set
if [ -z "${VGL_DISPLAY-}" ]; then
	# Use the dummy X server if it is enabled
	if [ "${ENABLE_XDUMMY:?}" = 'true' ]; then
		export VGL_DISPLAY=:0.0
	# Otherwise try to use the EGL backend
	else
		for card in /dev/dri/card*; do
			if /opt/VirtualGL/bin/eglinfo -B "${card:?}" 2>/dev/null; then
				export VGL_DISPLAY="${card:?}"
				break
			fi
		done
	fi
fi

# Generate SSH keys if they do not exist
if [ ! -f /etc/ssh/ssh_host_ed25519_key ]; then
	ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N '' >/dev/null
fi
if [ ! -f /etc/ssh/ssh_host_rsa_key ]; then
	ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N '' >/dev/null
fi

# Generate RDP certificate if it does not exist
if [ ! -f "${XRDP_TLS_KEY_PATH:?}" ] || [ ! -f "${XRDP_TLS_CRT_PATH:?}" ]; then
	FQDN=$(hostname --fqdn)

	(umask 077 \
		&& openssl ecparam -genkey -name prime256v1 > "${XRDP_TLS_KEY_PATH:?}" \
	) >/dev/null

	(umask 022 \
		&& openssl req -x509 -sha256 -days 3650 -subj "/CN=${FQDN:?}" -addext "subjectAltName=DNS:${FQDN:?}" -key "${XRDP_TLS_KEY_PATH:?}" > "${XRDP_TLS_CRT_PATH:?}" \
	) >/dev/null
fi

# Print RDP certificate fingerprint
openssl x509 -in "${XRDP_TLS_CRT_PATH:?}" -noout -fingerprint -sha1
openssl x509 -in "${XRDP_TLS_CRT_PATH:?}" -noout -fingerprint -sha256

# Dump environment variables
env | grep -Ev '^(PWD|OLDPWD|HOME|USER|SHELL|TERM|([^=]*(PASSWORD|SECRET)[^=]*))=' | sort > /etc/environment

# Start runit
exec tini -- runsvdir -P /etc/service/
