#!/bin/bash

SCRIPT_VER="1.1"

APP="Whisparr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Whisparr/version.id" ] && cat "/opt/Whisparr/version.id" || echo """
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" "http://whisparr.servarr.com/v1/update/nightly/updatefile?os=linux&runtime=netcore&arch=x64" | sed -e "s/^.*fileName=\(Whisparr\.develop\..*-x64\.tar\.gz\).*$/\1/" | sed -e "s/^Whisparr\.[^0-9]*\.\([0-9.]*\)\.linux-core-x64\.tar\.gz$/\1/""
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=6969
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}
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/whisparr"
APP_HOME="/opt/Whisparr"

while : ; do

    main_rc=1

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

    [ -d "${USERHOME}" ] || break

    APT_INSTALL "curl" "sqlite3" || break

    #
    # https://github.com/Whisparr/Whisparr
    # https://wiki.servarr.com/whisparr
    #

    _need_start="no"
    if systemctl is-active "${APP,,}@${USERNAME}" > /dev/null 2>&1 ; then
        _need_start="yes"
        SVC_DISABLE "${APP,,}@${USERNAME}"
        SVC_STOP    "${APP,,}@${USERNAME}"
    fi

    if [ -d "${APP_HOME}" ] ; then
        INFO "Installing ${APP} into ${APP_HOME}"
        _url="http://whisparr.servarr.com/v1/update/nightly/updatefile?os=linux&runtime=netcore&arch=x64"
        _ver="$( \
            curl -Ls -m 30 -o /dev/null -w "%{url_effective}" "${_url}" \
                | sed -e "s/^.*fileName=\(Whisparr\.develop\..*-x64\.tar\.gz\).*$/\1/" \
                | sed -e "s/^Whisparr\.[^0-9]*\.\([0-9.]*\)\.linux-core-x64\.tar\.gz$/\1/" )"
        if [ -z "${_ver}" ] ; then
            ERROR "Failed to retrieve ${APP} release tarball URL !"
            break
        fi
        RUN_LOG "wget --content-disposition '${_url}' -O '${TMP_DIR}/${APP}.tar.gz'"
        TAR_ZXF "${TMP_DIR}/${APP}.tar.gz" "/opt/" || break
        echo "${_ver}" > "${APP_HOME}/version.id"
        CHOWN_DIR root:root "${APP_HOME}" || break
    fi

    if [ "${_need_start}" = "yes" ] ; then
        SVC_ENABLE "${APP,,}@${USERNAME}"
        SVC_START  "${APP,,}@${USERNAME}"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
