#!/bin/bash

SCRIPT_VER="1.8"

APP="Flood"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
SUPPORTED_ON="Debian10,Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
DAEMON_PORT=3000
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}/flood"

while : ; do

    main_rc=1

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

    APT_INSTALL "gcc" "g++" "make" || break

#    APT_INSTALL "curl" "wget" "gcc" "g++" "make" || break
#    RUN_LOG "wget -qO- https://deb.nodesource.com/setup_lts.x | bash -" || break
#    APT_INSTALL "nodejs" || break

    NODEJS_INSTALL || break

    FLOOD_PORT="$(( USERUID - FIRST_UID + 3000 ))"
    RTORRENT_SCGI_PORT="$(( USERUID - FIRST_UID + 5000 ))"
    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        _baseURI="/flood"
    else
        _baseURI="/flood-${USERNAME}"
    fi

    GIT_CLONE "https://github.com/jesec/flood" "${APP_DIRECTORY}" || break
    RUN_LOG "git config --global --add safe.directory ${APP_DIRECTORY}" || break

    oWD="$( pwd )"
    cd "${APP_DIRECTORY}"
    RUN_LOG "npm install 2>&1" || break
#    RUN_LOG "npm audit fix 2>&1" || break
    RUN_LOG "npm audit fix 2>&1"
    RUN_LOG "npm run build 2>&1" || break
    cd "${oWD}"

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

    # SystemD service unit
    if [ ! -e "/etc/systemd/system/flood@.service" ] ; then
        cat <<-EOF > "/etc/systemd/system/flood@.service"
	[Service]
	WorkingDirectory=/home/%I/flood
	ExecStart=/usr/bin/npm start -- \\
	            --baseuri "${_baseURI}" \\
	            --port "${FLOOD_PORT}" \\
	            --auth "none" \\
	            --rthost "127.0.0.1" \\
	            --rtport "${RTORRENT_SCGI_PORT}" \\
	            --allowedpath "${USERHOME}/Downloads"
	Restart=always
	StandardOutput=null
	#StandardOutput=syslog
	#StandardError=syslog
	#SyslogIdentifier=notell
	User=%I
	Group=%I
	Environment=NODE_ENV=production

	[Install]
	WantedBy=multi-user.target
	EOF
        SYSTEMD_RELOAD
    fi

    # Apache reverse proxy config
    if [ -d "/etc/apache2/userconf-enabled" ] ; then
        cat <<-EOF > "/etc/apache2/userconf-enabled/flood-${USERNAME}.conf" 2>> "${LOGFILE}"
	RewriteEngine on
	RewriteRule ^${_baseURI}$ ${_baseURI}/ [R=permanent]
	ProxyRequests off
	<Location ${_baseURI}/>
	   ProxyPreserveHost Off
	   ProxyPass http://127.0.0.1:${FLOOD_PORT}${_baseURI}/
	   ProxyPassReverse http://127.0.0.1:${FLOOD_PORT}${_baseURI}/
	   Order Allow,Deny
	   Allow from All
	   AuthType Digest
	   AuthName "apache2"
	   AuthUserFile /etc/apache2/users.password
	   Require user ${USERNAME}
	</Location>
	EOF
        SVC_RESTART "apache2" || break
    fi

    SVC_ENABLE "flood@${USERNAME}" || break
    SVC_START  "flood@${USERNAME}" || break


    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 "flood@${USERNAME}"
    SVC_STOP    "flood@${USERNAME}"
    [ -e "${APP_DIRECTORY}" ] \
        && RM_DIRS "${APP_DIRECTORY}"
    if [ -e "/etc/apache2/userconf-enabled/flood-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/flood-${USERNAME}.conf"
    fi
fi

SCRIPTEXIT
