#!/bin/bash
set -e

# Set user password from environment variable
/usr/local/bin/set-password.sh

# Store VNC password
mkdir -p /home/openbox/.vnc
x11vnc -storepasswd "${RDP_PASSWORD}" /home/openbox/.vnc/passwd
chown -R openbox:openbox /home/openbox/.vnc

# Pass environment variables to the openbox user session
echo "export FIREFOX_HOMEPAGE=\"${FIREFOX_HOMEPAGE}\"" > /home/openbox/.bashrc
chown openbox:openbox /home/openbox/.bashrc

# Ensure Firefox profile directory exists and has correct ownership
mkdir -p /home/openbox/.mozilla
chown -R openbox:openbox /home/openbox/.mozilla

# Prepare X11 socket directory
mkdir -p /tmp/.X11-unix
chmod 1777 /tmp/.X11-unix

# Generate XRDP RSA key if missing
if [ ! -f /etc/xrdp/rsakeys.ini ]; then
    xrdp-keygen xrdp auto
fi

# Start services via supervisor
exec /usr/bin/supervisord -c /etc/supervisord.conf
