#!/bin/bash

SCRIPT_VER="1.2"

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"
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


    RCW_DAEMON_PORT="$(( USERUID + DAEMON_PORT - FIRST_UID ))"

    # -- 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

    # -- Configure `systemd` service unit
    cat <<-EOF > "/etc/systemd/system/rclonewebui@.service" 2>> "${LOGFILE}"
	[Unit]
	Description=Rclone WebUI Daemon (%I)
	After=network.target

	[Service]
	User=%I
	Group=%I
	Restart=always
	RestartSec=5
	Type=simple
	ExecStart=/usr/local/bin/rclone rcd \\
	             --log-file "${USERHOME}/log/rclone.log" \\
	             --rc-web-gui \\
	             --rc-web-gui-no-open-browser \\
	             --rc-baseurl /rclone \\
	             --rc-htpasswd "/etc/apache2/users.basic.password" \\
	             --rc-addr=127.0.0.1:${RCW_DAEMON_PORT} \\
	             --rc-serve

	TimeoutStopSec=20

	[Install]
	WantedBy=multi-user.target
	EOF

    cat <<-EOF > "/etc/systemd/system/rclonewebui.slice" 2>> "${LOGFILE}"
	[Unit]
	Description=${APP} resource limiting
	Before=slices.target

	[Slice]
	CPUAccounting=yes
	CPUQuota=20%
	IOAccounting=yes
	IOReadBandwidthMax=/ 20M
	IOWriteBandwidthMax=/ 20M
	EOF

    [ ! -d "/etc/systemd/system/rclonewebui@.service.d" ] \
        && MKDIR "/etc/systemd/system/rclonewebui@.service.d"

    cat <<-EOF > "/etc/systemd/system/rclonewebui@.service.d/001-Slice.conf"
	[Service]
	Slice=syncthing.slice
	EOF

    cat <<-EOF > "/etc/systemd/system/rclonewebui@.service.d/10-Nice.conf"
	[Service]
	Nice=19
	EOF

    SYSTEMD_RELOAD

    SVC_ENABLE "rclonewebui@${USERNAME}"
    SVC_START  "rclonewebui@${USERNAME}"

    # -- Configure Apache ('/subfolder' scheme)
    cat <<-EOF > "/etc/apache2/userconf-enabled/rclonewebui.conf"
	RewriteEngine on
	RewriteRule ^/rclone$ /rclone/ [R=permanent]
	ProxyRequests off
	<Location /rclone/>
	    ProxyPreserveHost On
	    RequestHeader unset Accept-Encoding
	    ProxyPass http://127.0.0.1:${RCW_DAEMON_PORT}/rclone/
	    ProxyPassReverse http://127.0.0.1:${RCW_DAEMON_PORT}/rclone/
	    AllowOverride None
	    Allow from all
	    Satisfy any
	</Location>
	EOF
    SVC_RELOAD "apache2"


    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 "rclonewebui@${USERNAME}"
    SVC_STOP    "rclonewebui@${USERNAME}"
    RM_FILES    "/etc/systemd/system/rclonewebui@.service" \
                "/etc/systemd/system/rclonewebui.slice"
    RM_DIRS     "/etc/systemd/system/rclonewebui@.service.d"
    SYSTEMD_RELOAD
fi

SCRIPTEXIT
