#!/usr/bin/env bash

ENABLED=yes
[[ ${ENABLED} == yes ]] || exit 0
DEBUGMODE=no

SOURCE=/usr/lib/ublinux/functions; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null  || exit 0
SOURCE=/usr/lib/ublinux/os-config; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null  || exit 0
SOURCE=${SYSCONF}/config; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null
SOURCE=${SYSCONF}/desktop; [[ -f ${SOURCE} ]] && . ${SOURCE} 2>/dev/null

debug_mode "$0" "$@"

    if [[ -n ${X11VNC_PASSWORD} ]]; then
        [[ -d /root/.vnc ]] || mkdir -p /root/.vnc
        /usr/bin/x11vnc -storepasswd "$(base64 -d <<< "${X11VNC_PASSWORD}")" /root/.vnc/passwd
        chmod 600 /root/.vnc/passwd
        # Show obscured password
    	#/usr/bin/x11vnc -showrfbauth /root/.vnc/passwd
	if systemctl --quiet is-enabled lightdm-plymouth.service; then
	    for ID_DISPLAY in /var/run/lightdm/root/:*; do
		if systemctl --quiet is-enabled lightdm.service || systemctl --quiet is-enabled lightdm-plymouth.service; then
		    FILE_X11VNC_SERVICE="/usr/lib/systemd/system/x11vnc-ublinux:${ID_DISPLAY##*:}.service"
    		    mkdir -p "${FILE_X11VNC_SERVICE%/*}"
		    cat << EOF > "${FILE_X11VNC_SERVICE}"
[Unit]
Description=VNC Server for X11:${ID_DISPLAY##*:}
Requires=graphical.target
After=graphical.target

[Service]
#ExecStartPre=/bin/sh -c 'while ! pgrep -U "root" Xorg; do sleep 2; done'
ExecStart=
ExecStart=/usr/bin/x11vnc -many -shared  -display :${ID_DISPLAY##*:} -autoport 590${ID_DISPLAY##*:} -no6 -rfbauth /root/.vnc/passwd -auth /var/run/lightdm/root/:${ID_DISPLAY##*:} -o /var/log/x11vnc.log
#ExecStart=/usr/bin/x11vnc -many -shared -display %i -rfbport 590%i -forever -dontdisconnect -noxdamage -xkb -auth /var/run/lightdm/root/:0  -o /var/log/x11vnc.log
Restart=always
RestartSec=5
SuccessExitStatus=2

[Install]
WantedBy=graphical.target
EOF
		    [[ -f ${FILE_X11VNC_SERVICE} ]] && systemctl enable --now ${FILE_X11VNC_SERVICE##*/}
		elif systemctl --quiet is-enabled gdm.service || systemctl --quiet is-enabled gdm-plymouth.service; then
		    true
		elif systemctl --quiet is-enabled lxdm.service || systemctl --quiet is-enabled lxdm-plymouth.service; then
		    true
		elif systemctl --quiet is-enabled sddm.service || systemctl --quiet is-enabled sddm-plymouth.service; then
		    true
		elif systemctl --quiet is-enabled slim.service || systemctl --quiet is-enabled slim-plymouth.service; then
		    true
		fi
	    done
	fi
    else 
	rm -f /usr/lib/systemd/system/x11vnc-ublinux:*.service
    fi
