#!/bin/bash

SCRIPT_VER="2.0"

APP="Flood"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
#><#APP_UPGRADE_VER_CMD="curl -Ls -m 30 -o /dev/null -w "%{url_effective}" https://github.com/jesec/flood/releases/latest | awk -F "/" "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.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}/.local/share/flood"

while : ; do

    main_rc=1

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

    APT_INSTALL "curl" "wget" "jq" || break

    GITHUB_RELEASE "jesec/flood" "latest" "amd64" "deb" || break
    _url="${GITHUB_RELEASE_ASSET_URL}"
    if [ -n "${_url}" ] ; then
        WGET "${_url}" "${TMP_DIR}/flood.deb" || break
        DPKG_INSTALL "${TMP_DIR}/flood.deb" || break
    else
        ERROR "Unable to find Flood .deb package on GitHub"
        break
    fi

    # Update SystemD service if it uses npm
    if [ -e "/etc/systemd/system/flood@.service" ] ; then
        if grep -q "npm start" "/etc/systemd/system/flood@.service" ; then
            INFO "Updating SystemD service unit to use binary..."
            sed -i 's|ExecStart=/usr/bin/npm start -- \\|ExecStart=/usr/bin/flood \\|' "/etc/systemd/system/flood@.service"
            SYSTEMD_RELOAD
        fi
    fi

    # Restart service 'flood@'
    SVC_STATUS "flood@${USERNAME}" \
        && SVC_RESTART "flood@${USERNAME}"

    main_rc=0
    break

done


SCRIPTEXIT
