#!/bin/bash

# === Variables ===
USERNAME="dbi"
USERPASS=""  # ⚠️ Modifie ce mot de passe si nécessaire
LOCALE="en_US.UTF-8"
KEYMAP="fr be"

echo "🔧 Mise à jour du système"
apt update && apt upgrade -y

echo "📦 Installation des dépendances"
apt install -y sudo curl wget gnupg2 software-properties-common dbus-x11 \
xfce4 xfce4-goodies lightdm xrdp gnome-keyring libsecret-1-0 firefox-esr

echo "🌍 Configuration de la locale ($LOCALE)"
sed -i "s/^# $LOCALE UTF-8/$LOCALE UTF-8/" /etc/locale.gen
locale-gen
update-locale LANG=$LOCALE

echo "🎯 Configuration de la session utilisateur XFCE"
USER_HOME="/home/$USERNAME"

# .xsession (environnement graphique + clavier + gnome-keyring + VS Code)
cat <<EOF > "$USER_HOME/.xsession"
export LANG=$LOCALE
export LANGUAGE=en_US
export LC_ALL=$LOCALE
setxkbmap $KEYMAP
eval \$(/usr/bin/gnome-keyring-daemon --start)
export SSH_AUTH_SOCK
startxfce4
EOF
chown "$USERNAME:$USERNAME" "$USER_HOME/.xsession"

echo "🚀 Ajout d'un autostart VS Code (avec délai et maximisé)"
mkdir -p "$USER_HOME/.config/autostart"
cat <<EOF > "$USER_HOME/.config/autostart/vscode.desktop"
[Desktop Entry]
Type=Application
Name=VS Code
Exec=bash -c "sleep 2 && code --maximized"
Terminal=false
StartupNotify=true
EOF
chown -R "$USERNAME:$USERNAME" "$USER_HOME/.config"

echo "🔐 Fix PolicyKit pour colord (boîte de dialogue)"
mkdir -p /etc/polkit-1/localauthority/50-local.d

cat <<EOF > /etc/polkit-1/localauthority/50-local.d/45-allow-colord.pkla
[Allow colord for all users]
Identity=unix-user:*
Action=org.freedesktop.color-manager.create-device
ResultAny=no
ResultInactive=no
ResultActive=yes
EOF

cat <<EOF > /etc/polkit-1/localauthority/50-local.d/46-allow-colord-profile.pkla
[Allow colord profile management for all users]
Identity=unix-user:*
Action=org.freedesktop.color-manager.create-profile
ResultAny=no
ResultInactive=no
ResultActive=yes
EOF

echo "🧠 Installation de VS Code Desktop (via dépôt Microsoft)"
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg
install -o root -g root -m 644 microsoft.gpg /usr/share/keyrings/
rm microsoft.gpg

echo "deb [arch=amd64 signed-by=/usr/share/keyrings/microsoft.gpg] \
https://packages.microsoft.com/repos/code stable main" > /etc/apt/sources.list.d/vscode.list

apt update
apt install -y code

echo "🔁 Redémarrage des services"
systemctl enable xrdp
systemctl restart xrdp
systemctl restart colord

echo "✅ Installation terminée"