#!/bin/bash

#set -x

SCRIPT_VER="1.16"

APP="ThinLinc"
APP_CATEGORY="Remote Access"
APP_SCOPE="system"
APP_ENABLED="yes"
SYS_PKG_NAME="thinlinc-server"
STORED_PASSWORD_SERVICE="user"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
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

APP_DIRECTORY="/opt/thinlinc"

while : ; do

    main_rc=1

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

    if [ -e "/etc/monit/conf.d/tlwebaccess" ] ; then
        RM_FILES "/etc/monit/conf.d/tlwebaccess"
        SVC_STATUS "monit" && MONIT_RELOAD
    fi

    SVC_DISABLE "tlwebadm"    ; SVC_STOP "tlwebadm"
    SVC_DISABLE "tlwebaccess" ; SVC_STOP "tlwebaccess"
    SVC_DISABLE "vsmagent"    ; SVC_STOP "vsmagent"
    SVC_DISABLE "vsmserver"   ; SVC_STOP "vsmserver"

    if DPKG_CHECK "thinlinc-server" ; then
        APT_REMOVE "thinlinc-server" || break
        RUN_LOG "apt-get -y -f install" || break
        APT_AUTOREMOVE || break
    fi

    _legacy_pkglist=""
    for _pkg in \
        "thinlinc-webaccess" \
        "thinlinc-tladm" \
        "thinlinc-vnc-server" \
        "thinlinc-rdesktop" \
        "thinlinc-tlprinter" \
        "thinlinc-vsm" \
        "thinlinc-tlmisc-libs" \
        "thinlinc-tlmisc-libs32" \
        "thinlinc-tlmisc" \
    ; do
        DPKG_CHECK "${_pkg}" && _legacy_pkglist="${_legacy_pkglist} ${_pkg}"
    done
    if [ -n "${_legacy_pkglist}" ] ; then
        APT_REMOVE ${_legacy_pkglist} || break
        RUN_LOG "apt-get -y -f install" || break
        APT_AUTOREMOVE || break
    fi

    _pids=""
    for _p in $( lsof 2> /dev/null | awk '/thinlinc/ {print $2}' | sort -u )
    do
        _pids="${_pids} ${_p}"
    done
    if [ -n "${_pids}" ] ; then
        L_LOG_START
        INFO "Killing processes: ${_pids}"
        RUN_LOG "kill -9 ${_pids}" || break
        L_LOG_FINISH
    fi

    RM_DIRS "${APP_DIRECTORY}" "/var/run/thinlinc" "/var/opt/thinlinc"

    SYSTEMD_RELOAD

    main_rc=0
    break

done


SCRIPTEXIT
