#!/bin/bash

SCRIPT_VER="1.3"

APP="Readarr"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="user"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Readarr/version.id" ] && cat "/opt/Readarr/version.id" || echo """
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
DAEMON_PORT=8787
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/readarr"
APP_HOME="/opt/Readarr"

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/Readarr/Readarr
    #

    if [ ! -e "${APP_HOME}/version.id" ] ; then
        if [ -d "${APP_HOME}" ] ; then
            RM_DIRS "${APP_HOME}"
        fi
        INFO "Installing ${APP} into ${APP_HOME}"
        _url="https://readarr.servarr.com/v1/update/develop/updatefile?os=linux&runtime=netcore&arch=x64"
        _ver="$( \
            curl -Ls -m 30 -o /dev/null -w "%{url_effective}" "${_url}" \
                | sed -e "s/^.*filename%3D\(Readarr.*-x64\.tar\.gz\).*$/\1/" \
                | sed -e "s/^Readarr\.[^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
#        RUN_LOG "find ${APP_HOME} -type d -exec chmod 755 {} \;"
#        RUN_LOG "find ${APP_HOME} -type f -exec chmod 755 {} \;"
    fi

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

    APP_DAEMON_PORT="$(( USERUID + 8787 - FIRST_UID ))"

    cat <<-EOF > "/etc/systemd/system/${APP,,}@.service"
	[Unit]
	Description=${APP} Daemon
	After=syslog.target network.target

	[Service]
	User=%i
	Group=%i
	Type=simple
	ExecStart=/opt/${APP}/${APP} -nobrowser -data=/home/%i/.config/${APP,,}
	TimeoutStopSec=20
	KillMode=process
	Restart=on-failure

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/${APP,,}.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/${APP,,}@.service.d" ] \
        && MKDIR "/etc/systemd/system/${APP,,}@.service.d"

    cat <<-EOF > "/etc/systemd/system/${APP,,}@.service.d/001-Slice.conf"
	[Service]
	Slice=${APP,,}.slice
	EOF

    SYSTEMD_RELOAD

    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        cat <<-EOF > "${APP_DIRECTORY}/config.xml"
		<Config>
		  <Port>${APP_DAEMON_PORT}</Port>
		  <BindAddress>127.0.0.1</BindAddress>
		  <UrlBase>${APP,,}</UrlBase>
		  <EnableSsl>False</EnableSsl>
		  <LaunchBrowser>False</LaunchBrowser>
		  <UpdateAutomatically>False</UpdateAutomatically>
		</Config>
	EOF
    else
        cat <<-EOF > "${APP_DIRECTORY}/config.xml"
		<Config>
		  <Port>${APP_DAEMON_PORT}</Port>
		  <BindAddress>127.0.0.1</BindAddress>
		  <UrlBase>${APP,,}-${USERNAME}</UrlBase>
		  <EnableSsl>False</EnableSsl>
		  <LaunchBrowser>False</LaunchBrowser>
		  <UpdateAutomatically>False</UpdateAutomatically>
		</Config>
	EOF
    fi
    CHOWN_FILE "${USERNAME}":"${USERNAME}" "${APP_DIRECTORY}/config.xml" || break

    SVC_ENABLE "${APP,,}@${USERNAME}" || break
    SVC_START  "${APP,,}@${USERNAME}" || break

    # Configure Apache
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        [ -e "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" ] \
            && RM_FILES "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf"
        if [ "${USERUID}" = "${FIRST_UID}" ] ; then
            cat <<-EOF > "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" 2>> "${LOGFILE}"
		RewriteEngine on
		RewriteRule ^/${APP,,}$ /${APP,,}/ [R=permanent]
		ProxyPreserveHost on
		ProxyPass /${APP,,} http://localhost:${APP_DAEMON_PORT}/${APP,,} connectiontimeout=5 timeout=300
		ProxyPassReverse /${APP,,} http://localhost:${APP_DAEMON_PORT}/${APP,,}

		<Location /${APP,,}>
		    Order deny,allow
		    Deny from all
		    Allow from all
		    AuthType Digest
		    AuthName "apache2"
		    AuthDigestProvider file
		    AuthUserFile "/etc/apache2/users.password"
		    Require user ${USERNAME}
		</Location>
		EOF
        else
            cat <<-EOF > "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf" 2>> "${LOGFILE}"
		RewriteEngine on
		RewriteRule ^/${APP,,}-${USERNAME}$ /${APP,,}-${USERNAME}/ [R=permanent]
		ProxyPreserveHost on
		ProxyPass /${APP,,}-${USERNAME} http://localhost:${APP_DAEMON_PORT}/${APP,,}-${USERNAME} connectiontimeout=5 timeout=300
		ProxyPassReverse /${APP,,}-${USERNAME} http://localhost:${RADARR_DAEMON_PORT}/radarr-${USERNAME}

		<Location /${APP,,}-${USERNAME}>
		    Order deny,allow
		    Deny from all
		    Allow from all
		    ProxyPass http://127.0.0.1:${APP_DAEMON_PORT}/${APP,,}-${USERNAME}
		    ProxyPassReverse http://127.0.0.1:${APP_DAEMON_PORT}/${APP,,}-${USERNAME}
		    AuthType Digest
		    AuthName "apache2"
		    AuthDigestProvider file
		    AuthUserFile "/etc/apache2/users.password"
		    Require user ${USERNAME}
		</Location>
		EOF
        fi
        SVC_RELOAD "apache2"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
