#!/bin/bash

SCRIPT_VER="1.5"

APP="Sabnzbd"
APP_CATEGORY="Torrent Clients and Utilities"
APP_ENABLED="yes"
##><#APP_CHECK_VER_CMD="if [ -e /opt/sabnzbd/PKG-INFO ] ; then grep -e "^Version:" /opt/sabnzbd/PKG-INFO | awk "{print \$NF}" ; else echo "" ; fi"
#><#APP_CHECK_VER_CMD="if [ -d "/opt/sabnzbd/.git" ] ; then GIT_DIR="/opt/sabnzbd/.git" git describe --tags | awk -F"/" "{print \$NF}" | tr "-" "_" ; else echo "" ; fi"
SUPPORTED_ON="Debian10,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

APP_DIRECTORY="${USERHOME}/.sabnzbd"

while : ; do

    main_rc=1

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

    systemctl is-enabled "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_DISABLE "sabnzbd@root"
    systemctl is-active "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_STOP    "sabnzbd@root"
    [ -d "/root/.sabnzbd" ] \
        && RM_DIRS "/root/.sabnzbd"

    SVC_DISABLE "sabnzbd@${USERNAME}"
    SVC_STOP    "sabnzbd@${USERNAME}"

    RM_DIRS "${APP_DIRECTORY}"

    passwd_file="/etc/apache2/sabnzbd.users.password"
    grep -q -e "^${USERNAME}:SABnzbd:" "${passwd_file}" \
        && RUN_LOG "echo '/^${USERNAME}:SABnzbd:.*/d' | sed -f - -i '${passwd_file}'"

    # Reconfigure 'apache2' service
    __apache_restart="no"
    for __f in "sabnzbd.conf" "sabnzbd-${USERNAME}.conf" ; do
        if [ -e "${__f}" ] ; then
            RM_FILES "${__f}"
            __apache_restart="yes"
        fi
    done
    [ "${__apache_restart}" = "yes" ] && SVC_RESTART "${APACHE_SVC}"

    # It was last user?
    ret="$( find /home -type d -a -iwholename '*/.sabnzbd' )"
    if [ -z "${ret[@]}" ] ; then
        RM_FILES "/etc/systemd/system/sabnzbd@.service"
        RM_FILES "/etc/systemd/system/sabnzbd.slice"
        SYSTEMD_RELOAD
        RM_DIRS "/opt/sabnzbd"
        [ -e "/etc/apache2/sabnzbd.users.password" ] \
            && RM_FILES "/etc/apache2/sabnzbd.users.password"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
