#!/bin/bash

SCRIPT_VER="1.2"

APP="Pure FTPd"
APP_CATEGORY="System Services"
APP_SCOPE="system"
APP_ENABLED="yes"
SYS_PKG_NAME="pure-ftpd"
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

PURE_CFG_DIR="/etc/pure-ftpd"

while : ; do

    main_rc=1 

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

    # Remove RSB scripts
    for __sc in \
      "addftpuser" \
      "addmultipleftpusers" \
      "changeftppass" \
      "enable-fxp" \
      "disable-fxp" \
      "ftpmgr" \
      "pure-disable-tls" \
      "pure-enable-tls"
    do
        [ -e "/usr/local/bin/${__sc}" ] \
            && RM_FILES "/usr/local/bin/${__sc}"
        [ -e "/usr/local/bin/rsb-${__sc}" ] \
            && RM_FILES "/usr/local/bin/rsb-${__sc}"
    done

    # Configure 'fail2ban'
    if [ -f "/etc/fail2ban/jail.d/pure-ftpd.conf" ] ; then
        RM_FILES "/etc/fail2ban/jail.d/pure-ftpd.conf"
        SVC_STATUS "fail2ban" \
            && SVC_RESTART "fail2ban"
    fi

    # Configure 'logrotate'
    if [ -f "/etc/logrotate.d/pure-ftpd-configure" ] ; then
        RM_FILES "/etc/logrotate.d/pure-ftpd-configure"
    fi

    # Configure 'monit'
    if [ -f "/etc/monit/conf.d/pure-ftpd" ] ; then
        RM_FILES "/etc/monit/conf.d/pure-ftpd"
        MONIT_RELOAD
    fi

    # Configure 'rsb.init.d' start script
    if [ -f "/etc/rsb.init.d/pure-ftpd.sh" ] ; then
        RM_FILES "/etc/rsb.init.d/pure-ftpd.sh"
    fi


    # Disable/Stop service
    SVC_DISABLE "pure-ftpd"
    for __i in 1 2 3 4 5 ; do
        if SVC_STATUS "pure-ftpd" ; then
            INFO "Stopping 'pure-ftpd' service: try #${__i}"
            SVC_STOP "pure-ftpd"
        else
            break
        fi
    done

    ${PKG_REMOVE}   \
        "pure-ftpd" \
        "pure-ftpd-common"

    [ -d "${PURE_CFG_DIR}" ] \
        && RM_DIRS "${PURE_CFG_DIR}"

    [ -e "/etc/ssl/private/pure-ftpd.pem" ] \
        && RM_FILES "/etc/ssl/private/pure-ftpd.pem"



    main_rc=0 
    break

done


SCRIPTEXIT
