#!/bin/bash

SCRIPT_VER="1.8"

APP="Sabnzbd"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
#><#APP_CHECK_VER_CMD="if [ -d "/opt/sabnzbd/.git" ] ; then GIT_DIR="/opt/sabnzbd/.git" git describe --tags | awk -F"/" "{print \$NF}" | tr "-" "_" ; else echo "" ; fi"
#><#APP_UPGRADE_VER_CMD="wget -S --timeout=10 --tries=3 -vvv --spider https://github.com/sabnzbd/sabnzbd/tarball/master 2>&1 | grep filename= | awk "{print \$3}" | sed -e "s/filename=sabnzbd-sabnzbd-\([^-]*\).*\.tar\.gz/\1/" | sed "s/\(.*\)-.*/\1/""
SUPPORTED_ON="Debian10,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

VALIDATE_USER

APP_DIRECTORY="${USERHOME}/.sabnzbd"

while : ; do

    main_rc=1

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


    oWD=$( pwd )
    # --
    cd "/opt/sabnzbd" || break
    if [ ! -d "./.git" ] ; then
        RUN_LOG "git init" || break
        RUN_LOG "git config --global user.email 'user@example.com'" || break
        RUN_LOG "git config --global user.name 'Seedbox Admin'" || break
        RUN_LOG "git add ." || break
        RUN_LOG "git commit -m'RSB: initial commit'" || break
        RUN_LOG "git clean -f" || break
        RUN_LOG "git remote add origin 'https://github.com/sabnzbd/sabnzbd' -m master" || break
    fi
    RUN_LOG "git config --global --add safe.directory /opt/sabnzbd" || break
    RUN_LOG "git fetch --all" || break
    RUN_LOG "git reset --hard origin/master" || break
    RUN_LOG "git pull --no-edit origin master -f" || break
    # --
    RUN_LOG "pip3 install --upgrade pip" || break
    PIP3_INSTALL --upgrade "setuptools" || break
    RUN_LOG "pip3 install --upgrade -r '/opt/sabnzbd/requirements.txt'" || break
    # --
    cd "${oWD}"

    # -- Restart service 'sabnzbd@user'
    SVC_STATUS "sabnzbd@${USERNAME}" \
        && SVC_RESTART  "sabnzbd@${USERNAME}"


    main_rc=0
    break

done


SCRIPTEXIT
