#!/bin/bash

SCRIPT_VER="1.1"

APP="Readarr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Readarr/version.id" ] && cat "/opt/Readarr/version.id" || echo """
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
DAEMON_PORT=8787
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


APP_DIRECTORY="${USERHOME}/.config/readarr"
APP_HOME="/opt/Readarr"

while : ; do

    main_rc=1

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

    # -- Stop/disable service
    SVC_STOP "${APP,,}@${USERNAME}"
    SVC_DISABLE "${APP,,}@${USERNAME}"

    RM_DIRS "${APP_DIRECTORY}"

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

    # -- Configure Apache
    if [ -e "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf"
        SVC_RESTART "apache2"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
