#!/bin/bash

SCRIPT_VER="1.1"

APP="SickChill"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
SUPPORTED_ON="Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
STORED_PASSWORD_SERVICE="sickchill"
DAEMON_PORT=8087
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/sickchill"

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
    RUN_LOG "sudo -u ${USERNAME} pip3 install --ignore-installed -U sickchill" || break

    MKDIR "${APP_DIRECTORY}" || break

    # -- Configuration

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

    # -- Configure service
    cat <<-EOF > "${USERHOME}/.local/bin/SickChill-wrapper.sh"
	#!/bin/bash
	${USERHOME}/.local/bin/SickChill -q --nolaunch \\
	                                 --port ${SC_DAEMON_PORT} \\
	                                 --datadir=${APP_DIRECTORY}
	EOF
    cat <<-EOF > "/etc/systemd/system/sickchill@.service"
	[Unit]
	Description=SickChill Daemon

	[Service]
	User=%I
	Group=%I
	#Type=forking
	Type=simple
	GuessMainPID=no
	#EnvironmentFile=/home/%I/.config/sickchill/.systemd.env
	ExecStart=/bin/bash /home/%I/.local/bin/SickChill-wrapper.sh
	TimeoutStopSec=20s

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/sickchill.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/sickchill@.service.d" ] \
        && MKDIR "/etc/systemd/system/sickchill@.service.d"

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

    SYSTEMD_RELOAD

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

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

    RUN_LOG "sleep 10"

    SVC_STOP "sickchill@${USERNAME}"

    _password=""
    if [ -e "/var/local/passwd/${USERNAME}" ] ; then
        _password="$( awk -F: '$1 == "sickchill" {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 = \"sickchill\"/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 = ${SC_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 "sickchill@${USERNAME}"

    # -- Configure Apache site
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/sickchill.conf"
	<Location /sickchill>
	    AllowOverride None
	    Allow from all
	    Satisfy any
	    ProxyPass http://127.0.0.1:${SC_DAEMON_PORT}/sickchill
	    ProxyPassReverse http://127.0.0.1:${SC_DAEMON_PORT}/sickchill
	</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
    SVC_DISABLE "sickchill@${USERNAME}"
    SVC_STOP    "sickchill@${USERNAME}"
    RM_FILES    "/etc/systemd/system/sickchill@.service" \
                "${USERHOME}/.local/bin/SickChill-wrapper.sh"
    SYSTEMD_RELOAD
    RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
