#!/bin/bash

SCRIPT_VER="1.0"

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

while : ; do

    main_rc=1

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

    [ -d "${USERHOME}" ] || break

    MKDIR "${APP_DIRECTORY}" || break

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

    # -- Install Storm
    INFO "Installing ${APP} into ${APP_DIRECTORY}"
    _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                  https://github.com/relvacode/storm/releases/latest \
                | awk -F '/' '{print $NF}' | tr -d 'v' )"
    if [ -z "${_ver}" ] ; then
        ERROR "Failed to retrieve ${APP} release tarball URL !"
        break
    else
        # Example:
        # https://github.com/relvacode/storm/releases/download/v1.3.0/storm-v1.3.0-linux-amd64.tar.gz
        APP_URL="https://github.com/relvacode/storm/releases/download/v${_ver}/storm-v${_ver}-linux-amd64.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_DIRECTORY}/" || break
    echo "${_ver}" > "${APP_DIRECTORY}/version.id"
    CHOWN_DIR root:root "${APP_DIRECTORY}" || break

    cat <<-'EOF' > "/usr/local/sbin/storm-wrapper.sh"
	#!/bin/bash

	export PATH=/sbin:/bin:/usr/sbin:/usr/bin

	if [ ! -e "/etc/login.defs" ] ; then
	    >&2 echo "ERROR: /etc/login.defs: File not found"
	    exit 1
	fi

	FIRST_UID="$( grep -e '^UID_MIN\s*' "/etc/login.defs" | awk '{print $2}' )"

	if [ ! -e "${HOME}/.config/deluge/auth" ] ; then
	    >&2 echo "ERROR: ${HOME}/.config/deluge/auth: File not found"
	    exit 1
	fi

	DELUGE_RPC_KEY="$( grep -E '^localclient:' "${HOME}/.config/deluge/auth" 2> /dev/null \
	                       | awk -F: '{print $2}' )"
	if [ -z "${DELUGE_RPC_KEY}" ] ; then
	    >&2 echo "ERROR: Can't find 'localclient' account in ${HOME}/.config/deluge/auth"
	    exit 1
	fi

	USERUID="$( id -u "${USER}" 2>/dev/null )"
	DELUGE_DAEMON_PORT="$(( USERUID + 58846 - FIRST_UID ))"
	STORM_WEBUI_PORT="$(( USERUID + 8221 - FIRST_UID ))"

	BASEPATH="/storm"
	[ "${USERUID}" != "${FIRST_UID}" ] \
	    && BASEPATH="/storm-${USER}"

	/opt/storm/storm \
	       --listen="127.0.0.1:${STORM_WEBUI_PORT}" \
	       --base-path="${BASEPATH}" \
	       --hostname="127.0.0.1" \
	       --port="${DELUGE_DAEMON_PORT}" \
	       --deluge-version="v2" \
	       --username="localclient" \
	       --password="${DELUGE_RPC_KEY}"
	EOF
    CHMOD_FILE "0755" "/usr/local/sbin/storm-wrapper.sh"

    cat <<-EOF > "/etc/systemd/system/storm@.service"
	[Unit]
	Description=Storm - alternative WebUI for Deluge Daemon 
	After=network.target

	[Service]
	Type=simple
	User=%i
	Group=%i
	ExecStart=/usr/local/sbin/storm-wrapper.sh
	Restart=always
	TimeoutStopSec=300

	[Install]
	WantedBy=multi-user.target
	EOF

    SYSTEMD_RELOAD

    SVC_ENABLE  "storm@${USERNAME}"
    SVC_RESTART "storm@${USERNAME}"

    # -- Apache configuration
    if [ -d "/etc/apache2/userconf-enabled/" ] ; then
        STORM_WEBUI_PORT="$(( USERUID + 8221 - FIRST_UID ))"
        # --
	BASEPATH="storm"
	[ "${USERUID}" != "${FIRST_UID}" ] \
	    && BASEPATH="storm-${USER}"
        # --
        cat <<-EOF > "/etc/apache2/userconf-enabled/storm-${USERNAME}.conf"
	RewriteEngine on
	RewriteRule ^/${BASEPATH}$ /${BASEPATH}/ [R=permanent]
	ProxyPreserveHost on
	ProxyPass /${BASEPATH} http://127.0.0.1:${STORM_WEBUI_PORT}/${BASEPATH} connectiontimeout=5 timeout=300
	ProxyPassReverse /${BASEPATH} http://127.0.0.1:${STORM_WEBUI_PORT}/${BASEPATH}

	<Location /${BASEPATH}>
	   Order deny,allow
	   Deny from all
	   Allow from all
	   AuthType Digest
	   AuthName "apache2"
	   AuthDigestProvider file
	   AuthUserFile "/etc/apache2/users.password"
	   Require user user
	</Location>
	EOF
        # --
        systemctl is-active "${APACHE_SVC}" > /dev/null \
            && SVC_RELOAD "${APACHE_SVC}"
    fi


    main_rc=0
    break

done


SCRIPTEXIT
