apt install -y lightdm lightdm-gtk-greeter lightdm-gtk-greeter-settings \
  lightdm-settings xserver-xephyr tigervnc-standalone-server tigervnc-common tigervnc-tools

# remote access to the current desktop session.
# x11vnc -display :0 -auth /var/run/lightdm/root/:0

# Secure Access via SSH Tunnel
# For security, never expose VNC directly to the internet.

# Instead, use an SSH tunnel:
# ssh -L 5900:localhost:5900 user@your-server-ip

# Setup tigervnc for lightdm vnc connection.
conf_print_initd() {
  cat <<-'EOF'
#!/sbin/openrc-run

name="x0vncserver"
description="Remote desktop service (VNC) for :0 display"

depend() {
    need net
    after lightdm
}

command="/usr/bin/x0vncserver"
command_args="-display :0 -rfbauth /etc/vncpasswd"
command_user="root"
pidfile="/run/x0vncserver.pid"

start_pre() {
    if [ ! -f "${command_args##* }" ]; then
        eerror "VNC password file not found. Run vncpasswd /etc/vncpasswd/"
        return 1
    fi
}
EOF
}
conf_print_initd | sudo tee /etc/init.d/x0vncserver
chmod +x /etc/init.d/x0vncserver

rc-update add x0vncserver default

vncpasswd /etc/vncpasswd
chmod 600 /etc/vncpasswd

rc-service x0vncserver start

# Set the vnc section of lightdm config file
# https://wiki.archlinux.org/title/LightDM#VNC_Server
#!/bin/sh
CONF="/etc/lightdm/lightdm.conf"

# Ensure [VNCServer] section exists and set values
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#enabled=/enabled=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#command=/command=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#port=/port=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#listen-address=/listen-address=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#width=/width=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#height=/height=/' "$CONF"
sed -i '/^\[VNCServer\]/,/^\[.*\]/ s/^#depth=/depth=/' "$CONF"

# Set actual values (modify as needed)
sed -i 's/^enabled=.*/enabled=true/' "$CONF"
sed -i 's/^command=.*/command=Xvnc -rfbauth /etc/vncpasswd/' "$CONF"
sed -i 's/^port=.*/port=5900/' "$CONF"
sed -i 's/^listen-address=localhost/' "$CONF"
sed -i 's/^width=.*/width=1024/' "$CONF"
sed -i 's/^height=.*/height=768/' "$CONF"
sed -i 's/^depth=.*/depth=24/' "$CONF"

# config_file=/etc/lightdm/lightdm-gtk-greeter.conf

#typeset -A rules
#rules=(
#"theme-name" "Adwaita-dark"
#"icon-theme-name" "Adwaita"
#"cursor-theme" ${username}
#)
#
#for rule in "${!rules[@]}"; do
#	regex="s/^#\?\(${rule}\s*\).*$/\1 ${rules[${rule}]}/"
#	sed -i "${regex}" ${config_file};
#done
