#!/bin/bash

SCRIPT_VER="1.3"

APP="Rclone WebUI"
APP_CATEGORY="Sync Solutions"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
#><#APP_CHECK_VER_CMD="if [ -x /usr/local/bin/rclone ] ; then /usr/local/bin/rclone --version | head -1 | awk "{print \$NF}" | tr -d "v" ; else echo "" ; fi"
#><#APP_UPGRADE_VER_CMD="curl -Ls --connect-timeout 10 --retry 3 -m 30 -o /dev/null -w "%{url_effective}" https://github.com/rclone/rclone/releases/latest | awk -F "/" "{print \$NF}" | tr -d "v""
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.04"
DAEMON_PORT=5572
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

while : ; do

    main_rc=1 

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


    # -- Install `fuse`
    ${PKG_INSTALL} "fuse" || break
    grep -q -E '^user_allow_other' "/etc/fuse.conf" \
        || echo "user_allow_other" >> "/etc/fuse.conf"

    # -- Fetch latest `rclone`
    _rcw_ver="$( curl -Ls -m 30 -o /dev/null -w "%{url_effective}" \
                          https://github.com/rclone/rclone/releases/latest \
                     | awk -F "/" "{print \$NF}" | tr -d "v" )"
    if [ -z "${_rcw_ver}" ] ; then
        ERROR "Could not determine ${APP} version!"
        break
    fi
    INFO "Latest build: ${_rcw_ver}"

    [ -d "/media/cloud" ] || MKDIR "/media/cloud"
    CHOWN_FILE "${USERNAME}":"${USERNAME}" "/media/cloud" || break
    RUN_LOG "ln -svf /media/cloud ${USERHOME}/Downloads/__Cloud__ 2>&1" || break

    [ -d "/usr/local/share/man/man1" ] || MKDIR "/usr/local/share/man/man1"

    WGET "https://github.com/rclone/rclone/releases/download/v${_rcw_ver}/rclone-v${_rcw_ver}-linux-amd64.zip" \
         "${TMP_DIR}/rclone.zip" \
        || break
    UNZIP "${TMP_DIR}/rclone.zip" "${TMP_DIR}/" || break
    RUN_LOG "ls -al ${TMP_DIR}/" || break
    RUN_LOG "cp -vpf ${TMP_DIR}/rclone*/rclone /usr/local/bin/" || break
    RUN_LOG "cp -vpf ${TMP_DIR}/rclone*/rclone.1 /usr/local/share/man/man1/" || break

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


    main_rc=0 
    break

done


SCRIPTEXIT
