#!/usr/bin/env bash
# Export all variables
set -a

# Abort if an error is encountered
set -e

# SSH config
if [ -f ~/.ssh/id_ed25519 ]
then
    chmod 0600 ~/.ssh/id_ed25519
fi

# Create base directories
for dir in ssh config/tigervnc
do
    [ -d ~/.${dir} ] || mkdir -p ~/.${dir}/
done

# Configure tigervnc auth if MYVNC_VNCPASS is set
if [ ${MYVNC_VNCPASS} ]
then
    if [ ! -f ~/.config/tigervnc/passwd ]
    then
        echo "${MYVNC_VNCPASS}" | vncpasswd -f >~/.config/tigervnc/passwd
        chmod 0600 ~/.config/tigervnc/passwd
    fi
else
    MYVNC_PASSWORDLESS="-SecurityTypes none"
fi

# Remove VNCPASS env
unset MYVNC_VNCPASS

# VNC xstartup
install /dev/stdin ~/.config/tigervnc/xstartup <<- xstartup
#!/usr/bin/env bash
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
exec ${STARTXBIN}
xstartup

# Turn vnc sharing on/off
if [[ ${MYVNC_VNCSHARING} == "true" ]] || [[ ${MYVNC_VNCSHARING} == "1" ]]
then
    _MYVNC_VNCSHARING=alwaysshared
else
    _MYVNC_VNCSHARING=nevershared
fi

# VNC config
cat >~/.config/tigervnc/config <<- vncconfig
session=plasmax11
dpi=192
geometry=1920x1080
framerate=60
depth=32
${_MYVNC_VNCSHARING}
vncconfig

# Disable KDE screenlock
cat >~/.config/kscreenlockerrc <<- 'kscreenlockerrc'
[Daemon]
Autolock=false
LockOnResume=false
Timeout=0
kscreenlockerrc

# Read cli parameters, if any
exec "${@}" &

# Launch Tigervnc
/usr/bin/dbus-launch vncserver :0 ${MYVNC_PASSWORDLESS}
