#!/bin/bash

SCRIPT_VER="1.4"

APP="Sonarr (Latest)"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
#><#APP_CHECK_VER_CMD="[ -e "/opt/Sonarr-latest/version.id" ] && cat "/opt/Sonarr-latest/version.id" || echo """
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" https://github.com/Sonarr/Sonarr/releases/latest | awk -F/ "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04"
USE_APACHE2="yes"
DAEMON_PORT="9989"
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

APP_DIRECTORY="${USERHOME}/.config/sonarr-latest"
APP_HOME="/opt/Sonarr-latest"

while : ; do

    main_rc=1 

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


    # -- Stop running service instance
    systemctl is-active "sonarr-latest@${USERNAME}" > /dev/null \
        && SVC_STOP "sonarr-latest@${USERNAME}"


    # -- Install Sonarr (Latest)
    if [ ! -e "${APP_HOME}/version.id" ] ; then
        if [ -d "${APP_HOME}" ] ; then
            RM_DIRS "${APP_HOME}"
        fi
        INFO "Installing ${APP} into ${APP_HOME}"
        _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                          https://github.com/Sonarr/Sonarr/releases/latest \
                     | awk -F '/' '{print $NF}' | tr -d 'v' )"
        if [ -z "${_ver}" ] ; then
            ERROR "Failed to retrieve ${APP} release tarball URL !"
            break
        else
            APP_URL="https://github.com/Sonarr/Sonarr/releases/download/v${_ver}/Sonarr.main.${_ver}.linux-x64.tar.gz"
            INFO "${APP} release tarball URL: ${APP_URL}"
        fi
        if [ -z "${APP_URL}" ] ; then
            ERROR "Failed to parse ${APP} release tarball URL !"
            break
        else
            APP_ARCHIVE=$( echo "${APP_URL}" | awk -F "/" '{print $NF}' )
            INFO "${APP} release tarball: ${APP_ARCHIVE}"
        fi
        WGET "${APP_URL}" || break
        TAR_ZXF "${TMP_DIR}/${APP_ARCHIVE}" "${TMP_DIR}/" || break
        RUN_LOG "mv -f '${TMP_DIR}/Sonarr' '${APP_HOME}' 2>&1" || break
        echo "${_ver}" > "${APP_HOME}/version.id"
        CHOWN_DIR root:root "${APP_HOME}" || break
    fi

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

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

    MKDIR "${APP_DIRECTORY}" || break

    SONARR_SUBDIR="sonarr-latest"
    [ "${USERUID}" != "${FIRST_UID}" ] \
        && SONARR_SUBDIR="${SONARR_SUBDIR}-${USERNAME}"

    cat <<-EOF > "${APP_DIRECTORY}/config.xml"
	<Config>
	  <LogLevel>info</LogLevel>
	  <EnableSsl>False</EnableSsl>
	  <Port>${SONARR_DAEMON_PORT}</Port>
	  <UrlBase>${SONARR_SUBDIR}</UrlBase>
	  <BindAddress>127.0.0.1</BindAddress>
	  <UpdateAutomatically>False</UpdateAutomatically>
	  <AuthenticationMethod>External</AuthenticationMethod>
	  <Branch>main</Branch>
	</Config>
	EOF

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

    # -- Configure `sonarr-latest` service
    cat <<-EOF > "/etc/systemd/system/sonarr-latest.slice"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

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

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

	[Service]
	User=%i
	Group=%i
	UMask=0002
	Type=simple
	ExecStart=${APP_HOME}/Sonarr -nobrowser -data=/home/%i/.config/sonarr-latest
	TimeoutStopSec=20
	KillMode=process
	Restart=on-failure

	[Install]
	WantedBy=multi-user.target
	EOF

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

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

    # -- Enable / start "user" `sonarr-latest` service instance
    SYSTEMD_RELOAD
    SVC_ENABLE  "sonarr-latest@${USERNAME}"
    SVC_RESTART "sonarr-latest@${USERNAME}"


    # -- Configure Apache2 reverse proxy
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/sonarr-latest-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/${SONARR_SUBDIR}$ /${SONARR_SUBDIR}/ [R=permanent]
	ProxyPreserveHost on
	ProxyPass /${SONARR_SUBDIR} http://127.0.0.1:${SONARR_DAEMON_PORT}/${SONARR_SUBDIR} connectiontimeout=5 timeout=300
	ProxyPassReverse /${SONARR_SUBDIR} http://127.0.0.1:${SONARR_DAEMON_PORT}/${SONARR_SUBDIR}


	<Location /${SONARR_SUBDIR}>
	    Order Allow,Deny
	    Allow from All
	    AuthType Digest
	    AuthName "apache2"
	    AuthDigestProvider file
	    AuthUserFile "/etc/apache2/users.password"
	    Require user ${USERNAME}
	</Location>
	EOF
        # -- Reload `apache2` service
        systemctl is-active "apache2" > /dev/null \
            && SVC_RELOAD "apache2"
    fi


    main_rc=0 
    break

done


SCRIPTEXIT
