#!/bin/bash

SCRIPT_VER="1.1"

APP="ruTorrent - MediaStream Plugin"
APP_CATEGORY="Torrent Clients and Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
DEPENDS="ruTorrent (Latest)"
SUPPORTED_ON="Ubuntu20.04,Ubuntu22.04,Ubuntu24.04"
USE_APACHE2="yes"
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

PLUGINS_DIRECTORY="/var/www/rutorrent/plugins"
APP_DIRECTORY="/var/www/rutorrent/plugins/mediastream"

while : ; do

    main_rc=1

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

    if [ ! -d "${PLUGINS_DIRECTORY}" ] ; then
        ERROR "'${PLUGINS_DIRECTORY}': directory does not exist."
        ERROR "Is 'ruTorrent' installed?"
        ERROR "Can not continus. Exiting..."
        break
    fi

    ${PKG_INSTALL} "git-core" || break


    # install rutorrent-thirdparty-plugins
    GIT_CLONE "https://github.com/nelu/rutorrent-thirdparty-plugins" "${TMP_DIR}/rutorrent-thirdparty-plugins" \
        || break
    CP_DIR "${TMP_DIR}/rutorrent-thirdparty-plugins/mediastream" "${APP_DIRECTORY}" || 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
    [ -e "${APP_DIRECTORY}" ] && RM_DIRS "${APP_DIRECTORY}"
fi

SCRIPTEXIT
