#!/bin/bash

SCRIPT_VER="1.10"

APP="SickRage"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="no"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT=8082
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="/opt/sickrage"
APP_DIRECTORY="${USERHOME}/.config/sickrage"

while : ; do

    main_rc=1

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

    if [ "${USERUID}" != "${FIRST_UID}" ] ; then
        ERROR "Cannot install this application for the user account '${USERNAME}'"
        break
    fi

    ${PKG_INSTALL} \
        "python3" \
        "git-core" \
        "libffi-dev" \
      || break

#    PIP3_INSTALL --upgrade "pip" || break
#    PIP3_INSTALL --upgrade "setuptools" || break
##    PIP3_INSTALL --ignore-installed "sickrage" || break
#    RUN_LOG "sudo -H -u ${USERNAME} pip3 install --ignore-installed -U sickrage" || break

#    SICKRAGE="$( which sickrage 2>/dev/null )"
#    if [ -z "${SICKRAGE}" ] ; then
#        ERROR "Can't find 'sickrage' binary!"
#        break
#    fi

    # -- Disable/Stop obsolete instance(s)
    systemctl is-enabled "sickrage@root" > /dev/null 2>&1 \
        && SVC_DISABLE "sickrage@root"
    systemctl is-active "sickrage@root" > /dev/null 2>&1 \
        && SVC_STOP    "sickrage@root"

    MKDIR "${APP_DIRECTORY}" || break

    GIT_CLONE "https://github.com/SickRage/SickRage.git" \
              "${APP_DIRECTORY}" \
        || break
    RUN_LOG "python3 -m pip install --no-deps -r ${APP_DIRECTORY}/requirements.txt 2>&1" \
        || break

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"


    # -- Configuration

    SR_DAEMON_PORT="$(( USERUID + DAEMON_PORT - FIRST_UID ))"

    # -- Configure service
    cat <<-EOF > "${APP_DIRECTORY}/SickRage-wrapper.sh"
	#!/bin/bash

	python3 ${APP_DIRECTORY}/SiCKRAGE.py -q \\
	                                --nolaunch \\
	                                --host 127.0.0.1 \\
	                                --port ${SR_DAEMON_PORT} \\
	                                --web_root "/sickrage" \\
	                                --datadir=${APP_DIRECTORY}

	#python3 ${APP_DIRECTORY}/SiCKRAGE.py -q \\
	#                                --nolaunch \\
	#                                --port ${SR_DAEMON_PORT} \\
	#                                --datadir=${APP_DIRECTORY}
	EOF

#    WGET "${SUPPORT}/sickrage-conf" || break
#    CP_FILE "${TMP_DIR}/sickrage-conf" "${APP_DIRECTORY}/config.ini"
#
#    RUN_LOG "sed -i 's/web_root.*/web_root = \"sickrage\"/g' '${APP_DIRECTORY}/config.ini' 2>&1"
##    RUN_LOG "sed -i 's/web_host.*/web_host = 0.0.0.0/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_host.*/web_host = 127.0.0.1/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_port.*/web_port = ${SR_DAEMON_PORT}/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/handle_reverse_proxy.*/handle_reverse_proxy = 1/g' '${APP_DIRECTORY}/config.ini' 2>&1"

    # -- Configure service
    cat <<-EOF > "/etc/systemd/system/sickrage@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=SickRage Daemon

	[Service]
	User=%I
	Group=%I
	Type=simple
	GuessMainPID=no
	#ExecStart=/bin/bash /home/%I/.local/bin/SickRage-wrapper.sh
	ExecStart=/bin/bash /home/%I/.config/sickrage/SickRage-wrapper.sh
	TimeoutStopSec=20s

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/sickrage.slice" 2>> "${LOGFILE}"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

	[Slice]
	CPUAccounting=yes
	CPUQuota=20%
	IOAccounting=yes
	IOReadBandwidthMax=/ 20M
	IOWriteBandwidthMax=/ 20M
	EOF

    [ ! -d "/etc/systemd/system/sickrage@.service.d" ] \
        && MKDIR "/etc/systemd/system/sickrage@.service.d"

    cat <<-EOF > "/etc/systemd/system/sickrage@.service.d/001-Slice.conf"
	[Service]
	Slice=sickrage.slice
	EOF

    SYSTEMD_RELOAD

    CHOWN_DIR "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}"

    _password=""
    if [ -e "/var/local/passwd/${USERNAME}" ] ; then
        _password="$( awk -F: '$1 == "sickrage" {print $2}' "/var/local/passwd/${USERNAME}" )"
        [ -z "${_password}" ] \
            && _password="$( awk -F: -v u="${USERNAME}" \
                                  '$1 == u {print $2}' "/var/local/passwd/${USERNAME}" )"
    fi
    [ -z "${_password}" ] \
        && _password="${USERPASSWORD}"

    cat <<-EOF > "${APP_DIRECTORY}/config.ini"
	web_root = "sickrage"
	web_host = 127.0.0.1
	web_port = ${SR_DAEMON_PORT}
	web_username = "${USERNAME}"
	web_password = "${_password}"
	handle_reverse_proxy = 1
	EOF

    SVC_ENABLE "sickrage@${USERNAME}"
    SVC_START  "sickrage@${USERNAME}"

#    RUN_LOG "sleep 10"
#
#    SVC_STOP "sickrage@${USERNAME}"
#
#    _password=""
#    if [ -e "/var/local/passwd/${USERNAME}" ] ; then
#        _password="$( awk -F: '$1 == "sickrage" {print $2}' "/var/local/passwd/${USERNAME}" )"
#        [ -z "${_password}" ] \
#            && _password="$( awk -F: -v u="${USERNAME}" \
#                                  '$1 == u {print $2}' "/var/local/passwd/${USERNAME}" )"
#    fi
#    [ -z "${_password}" ] \
#        && _password="${USERPASSWORD}"
#
#    RUN_LOG "sed -i 's/web_root.*/web_root = \"sickrage\"/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_host.*/web_host = 127.0.0.1/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_port.*/web_port = ${SR_DAEMON_PORT}/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_username.*/web_username = \"${USERNAME}\"/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/web_password.*/web_password = \"${_password}\"/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#    RUN_LOG "sed -i 's/handle_reverse_proxy.*/handle_reverse_proxy = 1/g' '${APP_DIRECTORY}/config.ini' 2>&1"
#
#    SVC_RESTART "sickrage@${USERNAME}"

    # -- Configure Apache site
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/sickrage.conf"
	<Location /sickrage>
	    AllowOverride None
	    Allow from all
	    Satisfy any
	    ProxyPass http://127.0.0.1:${SR_DAEMON_PORT}/sickrage
	    ProxyPassReverse http://127.0.0.1:${SR_DAEMON_PORT}/sickrage
	</Location>
	EOF
        SVC_RELOAD  "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
    RM_DIRS "${APP_DIRECTORY}"
    systemctl is-enabled "sickrage@root" > /dev/null 2>&1 \
        && SVC_DISABLE "sickrage@root"
    systemctl is-active "sickrage@root" > /dev/null 2>&1 \
        && SVC_STOP    "sickrage@root"
    systemctl is-enabled "sickrage@${USERNAME}" > /dev/null 2>&1 \
        && SVC_DISABLE "sickrage@${USERNAME}"
    systemctl is-active "sickrage@${USERNAME}" > /dev/null 2>&1 \
        && SVC_STOP    "sickrage@${USERNAME}"
    RM_FILES    "/etc/systemd/system/sickrage@.service" \
                "/etc/systemd/system/sickrage.slice" \
                "${USERHOME}/.local/bin/SickRage-wrapper.sh"
    SYSTEMD_RELOAD
fi

SCRIPTEXIT
