#!/bin/bash

SCRIPT_VER="1.7"

APP="CherryMusic"
APP_CATEGORY="Streaming"
APP_SCOPE="user"
APP_ENABLED="yes"
CONFLICTS="I2P Daemon"
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

VALIDATE_USER

while : ; do

    main_rc=1

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

    # Disable/stop service
    SVC_DISABLE "cherrymusic@${USERNAME}"
    SVC_STOP    "cherrymusic@${USERNAME}"

    # Remove config & DB
    RM_DIRS "${USERHOME}/.config/cherrymusic"
    RM_DIRS "${USERHOME}/.local/share/cherrymusic"

    # Configure `apache2` service
    __apache_restart="no"
    if [ -e "/etc/apache2/userconf-enabled/cherrymusic-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/cherrymusic-${USERNAME}.conf"
        __apache_restart="yes"
    fi
    if [ -e "/etc/apache2/userconf-enabled/cherrymusic.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/cherrymusic.conf"
        __apache_restart="yes"
    fi
    if [ "${__apache_restart}" = "yes" ] ; then
        SVC_RESTART "apache2"
    fi

    # It was last user in Charrymusic? - Will delete Cherrymusic from machine....
    ret="$( find /home -type d -a -iwholename '*/.config/cherrymusic' )"
    if [ -z "${ret[@]}" ] ; then
        RM_FILES "/etc/systemd/system/cherrymusic@.service"
        [ -d "/etc/systemd/system/cherrymusic@.service.d" ] \
             && RM_DIRS "/etc/systemd/system/cherrymusic@.service.d"
        SYSTEMD_RELOAD
        PIPX_UNINSTALL "cherrymusic"
    fi

    main_rc=0
    break

done


SCRIPTEXIT
