#!/bin/bash

SCRIPT_VER="1.15"

APP="Sabnzbd"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
##><#APP_CHECK_VER_CMD="if [ -e /opt/sabnzbd/PKG-INFO ] ; then grep -m 1 -e "^Version:" /opt/sabnzbd/PKG-INFO | awk "{print \$NF}" ; else echo "" ; fi"
#><#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"
STORED_PASSWORD_SERVICE="sabnzbd"
SUPPORTED_ON="Debian10,Ubuntu20.04,Ubuntu22.04"
DAEMON_PORT=8085
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

    MKDIR "${APP_DIRECTORY}" || break
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"

    case "${LSB_VER}" in
      "Ubuntu18.04")
          DPKG_CHECK "python3-notify2" && APT_REMOVE "python3-notify2"
          ;;
    esac

    systemctl is-enabled "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_DISABLE "sabnzbd@root"
    systemctl is-active "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_STOP    "sabnzbd@root"
    [ -d "/root/.sabnzbd" ] \
        && RM_DIRS "/root/.sabnzbd"

    APT_INSTALL "p7zip-full" "unrar-free" || break

    if [ ! -d "/opt/sabnzbd" ] ; then
        APT_INSTALL "python3" "git-core" "par2" || break
        PIP3_INSTALL --upgrade "pip" || break
        PIP3_INSTALL --upgrade "setuptools" || break
        RUN_LOG "git clone 'https://github.com/sabnzbd/sabnzbd' -b master '/opt/sabnzbd'" || break
        RUN_LOG "git config --global --add safe.directory /opt/sabnzbd" || break
        RUN_LOG "pip3 install --upgrade pip" || break
        RUN_LOG "pip3 install --upgrade -r '/opt/sabnzbd/requirements.txt'" || break
    fi

    # Configure service
    cat <<-EOF > "/etc/systemd/system/sabnzbd@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=SABnzbd binary newsreader

	[Service]
	ExecStart=/opt/sabnzbd/SABnzbd.py -f /home/%I/.sabnzbd/sabnzbd.ini --logging 1 --browser 0
	User=%I
	Group=%I
	Slice=sabnzbd.slice

	[Install]
	WantedBy=multi-user.target
	EOF

    # -- Resource limiting to 20MB/s 
    cat <<-EOF > "/etc/systemd/system/sabnzbd.slice" 2>> "${LOGFILE}"
	[Unit]
	Description=Sabnzbd resource limiting
	Before=slices.target
 
	[Slice]
	CPUAccounting=yes
	CPUQuota=45%
	IOAccounting=yes
	IOReadBandwidthMax=/ 20M
	IOWriteBandwidthMax=/ 20M
	EOF

    SYSTEMD_RELOAD

    __sfx=""
    [ "${USERUID}" != "${FIRST_UID}" ] && __sfx="-${USERNAME}"

    S_DAEMON_PORT="$(( USERUID + 8085 - FIRST_UID ))"
    _conf_ver="$( grep -E '^__version__' /opt/sabnzbd/tests/data/sabnzbd.basic.ini | awk '{print $NF}' )"
#    cat <<-EOF > "${APP_DIRECTORY}/sabnzbd.ini"
#	__version__ = 19
#	__encoding__ = utf-8
#	[misc]
#	host = 127.0.0.1
#	port = ${S_DAEMON_PORT}
#	url_base = "/sabnzbd${__sfx}"
#	EOF
    cat <<-EOF > "${APP_DIRECTORY}/sabnzbd.ini"
	__version__ = 19
	__encoding__ = utf-8
	[misc]
	host = ""
	port = ${S_DAEMON_PORT}
	url_base = "/sabnzbd${__sfx}"
	check_new_rel = 0
	EOF
    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"

    SVC_ENABLE "sabnzbd@${USERNAME}" \
        && SVC_START "sabnzbd@${USERNAME}"

    passwd_file="/etc/apache2/sabnzbd.users.password"
    pline="$( \
        ( echo -n "${USERNAME}:SABnzbd:" && echo -n "${USERNAME}:SABnzbd:${USERPASSWORD}" \
           | md5sum | awk '{print $1}' \
        ) \
      )"
    if [ -e "${passwd_file}" ] ; then
        if grep -q -e "^${USERNAME}:SABnzbd:" "${passwd_file}" ; then
            RUN_LOG "echo 's#^${USERNAME}:SABnzbd:.*#${pline}#' | \
                        sed -f - -i '${passwd_file}'"
        else
            echo "${pline}" >> "${passwd_file}"
        fi
    else
        echo "${pline}" > "${passwd_file}"
    fi

    # Configure `apache2` service
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        [ -e "/etc/apache2/userconf-enabled/sabnzbd.conf" ] \
            && RM_FILES "/etc/apache2/userconf-enabled/sabnzbd.conf"
        cat <<-EOF > "/etc/apache2/userconf-enabled/sabnzbd-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/sabnzbd${__sfx}\$ /sabnzbd${__sfx}/ [R=permanent]
	<Location /sabnzbd${__sfx}>
	  order deny,allow
	  deny from all
	  allow from all
	  ProxyPass http://127.0.0.1:${S_DAEMON_PORT}/sabnzbd
	  ProxyPassReverse http://127.0.0.1:${S_DAEMON_PORT}/sabnzbd
	  AuthType Digest
	  AuthName "SABnzbd"
	  AuthDigestProvider file
	  AuthUserFile "/etc/apache2/sabnzbd.users.password"
	  Require user ${USERNAME}
	</Location>
	EOF
        SVC_RESTART "apache2"
    fi


    main_rc=0
    break

done



# Cleanup if error
if [ ${main_rc} -ne 0 -a ${main_rc} -ne 111 -a ${main_rc} -ne 117 ] ; then
    ERROR "'${APP}': Installation failed."
    # Cleanup tasks here
    systemctl is-enabled "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_DISABLE "sabnzbd@root"
    systemctl is-active "sabnzbd@root" > /dev/null 2>&1 \
        && SVC_STOP    "sabnzbd@root"
    [ -d "/opt/sabnzbd" ] \
        && RM_DIRS "/opt/sabnzbd"
    [ -d "/root/.sabnzbd" ] \
        && RM_DIRS "/root/.sabnzbd"
    SVC_DISABLE "sabnzbd@${USERNAME}"
    SVC_STOP    "sabnzbd@${USERNAME}"
    RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
