#!/bin/bash

SCRIPT_VER="1.3"

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

while : ; do

    main_rc=1 

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

    # -- Install required packages
    APT_INSTALL "uuid-runtime" "sqlite3" || break

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

    # -- Install Autobrr
    if [ ! -e "${APP_HOME}/version.id" ] ; then
        if [ -d "${APP_HOME}" ] ; then
            RM_DIRS "${APP_HOME}"
        fi
        MKDIR "${APP_HOME}" || break
        INFO "Installing ${APP} into ${APP_HOME}"
        _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                          https://github.com/autobrr/autobrr/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/autobrr/autobrr/releases/download/v${_ver}/autobrr_${_ver}_linux_x86_64.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}" "${APP_HOME}/" || break
        echo "${_ver}" > "${APP_HOME}/version.id"
        CHOWN_DIR root:root "${APP_HOME}" || break
    fi

    # -- Remove instance configuration directory if needed
    [ -d "${APP_DIRECTORY}" ] \
        && RM_DIRS "${APP_DIRECTORY}"

    # -- Configure Autobrr
    MKDIR "${APP_DIRECTORY}" || break

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

    APP_BASEURL="${APP,,}"
    [ "${USERUID}" != "${FIRST_UID}" ] \
        && APP_BASEURL="${APP_BASEURL}-${USERNAME}"

    cat <<-EOF > "${APP_DIRECTORY}/config.toml"
	# config.toml

	host = "127.0.0.1"
	port = ${APP_DAEMON_PORT}
	baseUrl = "/${APP_BASEURL}/"
	#logPath = "log/autobrr.log"
	#logMaxSize = 50
	#logMaxBackups = 3
	logLevel = "INFO"
	checkForUpdates = false
	sessionSecret = "$( uuidgen )"
	EOF

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


    # -- Configure SystemD service
    cat <<-EOF > "/etc/systemd/system/${APP,,}@.service"
	[Unit]
	Description=${APP} Daemon for %i
	After=network.target

	[Service]
	User=%i
	Group=%i
	Type=simple
	ExecStart=${APP_HOME}/autobrr --config=/home/%i/.config/autobrr/

	[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

    # -- Enable / start user's autobrr service instance
    SYSTEMD_RELOAD
    SVC_ENABLE  "${APP,,}@${USERNAME}"
    SVC_RESTART "${APP,,}@${USERNAME}"


    # -- Configure Apache2 reverse proxy
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/${APP,,}-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/${APP_BASEURL}$ /${APP_BASEURL}/ [R=permanent]
	ProxyRequests off
	<Location /${APP_BASEURL}/>
	   ProxyPreserveHost On
	   ProxyPass http://127.0.0.1:${APP_DAEMON_PORT}/
	   ProxyPassReverse http://127.0.0.1:${APP_DAEMON_PORT}/
	   Require all granted
	   Satisfy any
	</Location>
	EOF
        # -- Reload `apache2` service
        systemctl is-active "apache2" > /dev/null \
            && SVC_RELOAD "apache2"
    fi


    main_rc=0 
    break

done


SCRIPTEXIT
