#!/bin/bash

SCRIPT_VER="1.5"

APP="VNC"
APP_CATEGORY="Remote Access"
APP_ENABLED="yes"
SUPPORTED_ON="CentOS7,CentOS8,CentOSStream8,Debian9,Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
LIBRARY="functions4.sh"

if [ "${SUPPORT-}" = '' ]; then
    SUPPORT="https://installers.rapidseedbox.com/scripts/whmcs_client_installers/support"
fi

LOGFILE="/var/log/whmcs_client_installers/${0}.log"
[ ! -d "/var/log/whmcs_client_installers" ] && mkdir -p "/var/log/whmcs_client_installers"

wget -4 -nc -q --no-check-certificate --timeout=20 --tries=5 ${SUPPORT}/${LIBRARY} >> "${LOGFILE}" 2>&1
if [ ! -f "./${LIBRARY}" ] ; then
    echo "55"
    echo "Error downloading \"${SUPPORT}/${LIBRARY}\"" >> "${LOGFILE}"
    exit 55
fi

# shellcheck source=support/functions4.sh
. "./${LIBRARY}"
SCRIPTENTRY

VALIDATE_USER

APP_DIRECTORY="${USERHOME}/.vnc"
VNC_PORT="$(( USERUID - FIRST_UID + 5901 ))"

while : ; do

    main_rc=1

    CHECK_APP ; _rc=$?
    if [ ${_rc} -ne 0 ] ; then
        main_rc=${_rc}
        break
    fi

    # Configure 'monit'
    if [ -f "/etc/monit/conf.d/vncserver-${USERNAME}" ] ; then
        RM_FILES "/etc/monit/conf.d/vncserver-${USERNAME}"
        MONIT_RELOAD
    fi

    SVC_STOP    "vncserver-${USERNAME}"
    SVC_DISABLE "vncserver-${USERNAME}"
    if [ "${SVC_SYSTEM}" = "init" ] ; then
        RM_FILES "/etc/init.d/vncserver-${USERNAME}"
    elif [ "${SVC_SYSTEM}" = "systemd" ] ; then
        RM_FILES "/etc/systemd/system/vncserver-${USERNAME}.service"
        SYSTEMD_RELOAD
    fi

    # Remove config directory
    RM_DIRS "${APP_DIRECTORY}"

    # Configure firewall
    FW_REMOVE_PORTS "${VNC_PORT}/tcp"

    # Configure fail2ban - step #1
    if [ -e "/etc/fail2ban/jail.d/tighvnc-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/fail2ban/jail.d/tighvnc-${USERNAME}.conf"
        SVC_STATUS "fail2ban" && SVC_RESTART "fail2ban"
    fi

    # It was last user in VNC? - Will delete VNC from machine....
    ret="$( find /home -type d -a -iwholename '*/.vnc' )"
    if [ -z "${ret[@]}" ] ; then
        if [ "${LSB_VENDOR}" = "CentOS" ] || [ "${LSB_VENDOR}" = "CentOSStream" ] ; then
            YUM_REMOVE "tigervnc-server"
        elif   [ "${LSB_VENDOR}" = "Debian" ] \
            || [ "${LSB_VENDOR}" = "Devuan" ] \
            || [ "${LSB_VENDOR}" = "Ubuntu" ]
        then
            #
            APT_REMOVE "tightvncserver" "tightvnc-java"
            APT_AUTOREMOVE
        fi
        #
        # Configure fail2ban - step #2
        if [ -e "/etc/fail2ban/filter.d/tighvnc-auth.conf" ] ; then
            RM_FILES "/etc/fail2ban/filter.d/tighvnc-auth.conf"
            SVC_STATUS "fail2ban" && SVC_RESTART "fail2ban"
        fi
    fi


    main_rc=0
    break

done


SCRIPTEXIT
