#!/bin/bash

SCRIPT_VER="1.2"

APP="Sonarr (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Sonarr-latest/version.id" ] && cat "/opt/Sonarr-latest/version.id" || echo """
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" https://github.com/Sonarr/Sonarr/releases/latest | awk -F/ "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT="9989"
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}/.config/sonarr-latest"
APP_HOME="/opt/Sonarr-latest"

while : ; do

    main_rc=1 

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


    # -- Disable stop service instances
    systemctl is-enabled "sonarr-latest@${USERNAME}" > /dev/null \
        && SVC_DISABLE "sonarr-latest@${USERNAME}"
    systemctl is-active "sonarr-latest@${USERNAME}" > /dev/null \
        && SVC_STOP "sonarr-latest@${USERNAME}"

    RM_DIRS "${APP_DIRECTORY}"

    if [ -e "/etc/apache2/userconf-enabled/sonarr-latest-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/sonarr-latest-${USERNAME}.conf"
        SVC_RELOAD "apache2"
    fi


    # -- It was last user? - Will delete it from machine....
    ret="$( find /home -type d -a -iwholename '*/.config/sonarr-latest' )"
    if [ -z "${ret[@]}" ] ; then
        RUN_LOG "systemctl kill sonarr-latest.slice 2>&1"
        RUN_LOG "systemctl stop sonarr-latest.slice 2>&1"
        RM_FILES "/etc/systemd/system/sonarr-latest@.service" \
                 "/etc/systemd/system/sonarr-latest.slice"
        if [ -d "/etc/systemd/system/sonarr-latest@.service.d" ] ; then
             RM_DIRS "/etc/systemd/system/sonarr-latest@.service.d"
        fi
        SYSTEMD_RELOAD
        RM_DIRS "${APP_HOME}"
    fi


    main_rc=0 
    break

done


SCRIPTEXIT
