#!/bin/bash

sudo apt update
sudo apt install xrdp -y
sudo apt install xorgxrdp -y
sudo adduser xrdp ssl-cert
sudo systemctl enable xrdp
sudo ufw allow 3389/tcp
sudo apt install xfce4 xfce4-goodies -y

# Define the command to be written into .xsession file
SESSION_CMD="startxfce4"

# Directory where user home directories are located
HOMEDIR="/home"

# Ensure the script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root"
  exit 1
fi

# Iterate over all directories in /home, assuming they are user home directories
for USERDIR in $HOMEDIR/*; do
    # Skip non-directory entries (e.g., mount points or system directories)
    if [ ! -d "$USERDIR" ]; then
        continue
    fi

    # Extract username from directory path
    USERNAME=$(basename "$USERDIR")

    # Path to the .xsession file
    XSESSION_FILE="$USERDIR/.xsession"

    # Check if the user exists (to avoid processing non-user directories)
    if id "$USERNAME" &>/dev/null; then
        # If .xsession file doesn't exist or is empty, create or update it
        if [ ! -s "$XSESSION_FILE" ]; then
            echo "$SESSION_CMD" > "$XSESSION_FILE"  # Write the session command to the file
            chown "$USERNAME:$USERNAME" "$XSESSION_FILE"  # Set correct ownership
            chmod 644 "$XSESSION_FILE"  # Set appropriate permissions
            echo "Created/Updated .xsession for user: $USERNAME"
        else
            echo ".xsession already exists and is not empty for user: $USERNAME"
        fi
    else
        echo "Directory $USERDIR does not belong to a valid user, skipping."
    fi
done


sudo systemctl restart xrdp
sudo systemctl restart xrdp-sesman

