#!/bin/bash

SCRIPT_VER="1.7"

APP="Flood"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="user"
APP_ENABLED="yes"
#><#APP_UPGRADE_VER_CMD="wget -S --timeout=10 --tries=3 -vvv --spider https://github.com/jesec/flood/tarball/master 2>&1 | grep filename= | awk "{print \$3}" | sed -e "s/filename=jesec-flood-\(.*\)-.*\.tar\.gz/\1/" | sed "s/\(.*\)-.*/\1/" | tr "-" "_""
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 "curl" "wget" "gcc" "g++" "make" || break
    RUN_LOG "wget -qO- https://deb.nodesource.com/setup_lts.x | bash -" || break
    APT_INSTALL "nodejs" || break

    oWD=$( pwd )
    cd "${APP_DIRECTORY}" || break
    if [ ! -d "./.git" ] ; then
        RUN_LOG "git init" || break
        RUN_LOG "git config --global user.email 'user@example.com'" || break
        RUN_LOG "git config --global user.name 'Seedbox Admin'" || break
        RUN_LOG "git add ." || break
        RUN_LOG "git commit -m'RSB: initial commit'" || break
        RUN_LOG "git clean -f" || break
        RUN_LOG "git remote add origin 'https://github.com/jesec/flood'" || break
    fi
    RUN_LOG "git config --global --add safe.directory ${APP_DIRECTORY}" || break
    RUN_LOG "git fetch --all" || break
    RUN_LOG "git reset --hard origin/master" || break
    RUN_LOG "git pull --no-edit origin master -f" || break
    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}"

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


    main_rc=0
    break

done


SCRIPTEXIT
