#!/bin/bash

SCRIPT_VER="1.3"

APP="Librespeed"
APP_CATEGORY="Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
SUPPORTED_ON="Ubuntu16.04,Ubuntu18.04,Ubuntu20.04,Ubuntu22.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

APP_DIRECTORY="/var/www/librespeed"

while : ; do

    main_rc=1

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

    # -- Install reuired packeges
    APT_INSTALL "php-sqlite3" || break

    # -- Create application home directory
    MKDIR "${APP_DIRECTORY}"

    # -- Fetch and install the latest `librespeed/speedtest` package
    _ver="$( curl -Ls -m 30 -o /dev/null -w '%{url_effective}' \
                  https://github.com/librespeed/speedtest/releases/latest \
              | awk -F "/" '{print $NF}' )"
    if [ -z "${_ver}" ] ; then
        ERROR "Could not determine ${APP} version!"
        break
    fi
    INFO "Latest build: ${_ver}"
    WGET "https://github.com/librespeed/speedtest/archive/refs/tags/${_ver}.tar.gz" \
         "${TMP_DIR}/speedtest.tar.gz" \
        || break
    TAR_ZXF "${TMP_DIR}/speedtest.tar.gz" "${TMP_DIR}/" || break
    RUN_LOG "mv -vf ${TMP_DIR}/speedtest-${_ver}/* ${APP_DIRECTORY}/" || break

    if [ -e "${APP_DIRECTORY}/example-singleServer-gauges.html" ] ; then
        RUN_LOG \
            "cp -vf ${APP_DIRECTORY}/example-singleServer-gauges.html ${APP_DIRECTORY}/index.html" \
          || break
    elif [ -e "${APP_DIRECTORY}/examples/example-singleServer-gauges.html" ] ; then
        RUN_LOG \
            "cp -vf ${APP_DIRECTORY}/examples/example-singleServer-gauges.html ${APP_DIRECTORY}/index.html" \
          || break
    else
        ERROR "Can't find 'example-singleServer-gauges.html' template!"
        break
    fi
    RUN_LOG "sed -i -e 's|<title>LibreSpeed Example</title>|<title>RapidSeedbox SpeedTest</title>|; \
                        s|<h1>LibreSpeed Example</h1>|<h1>RapidSeedbox SpeedTest</h1>|' \
                 ${APP_DIRECTORY}/index.html"
    RUN_LOG "sed -e '/<a href=\"https:\/\/github.com\/librespeed.*<\/a>/d' \
                 ${APP_DIRECTORY}/index.html"
    cat <<-EOF > "${APP_DIRECTORY}/results/telemetry_settings.php"
	<?php
	\$db_type = 'sqlite';
	\$stats_password = 'pass';
	\$enable_id_obfuscation = false;
	\$redact_ip_addresses = false;
	\$Sqlite_db_file = '${APP_DIRECTORY}/speedtest_telemetry.sql';
	EOF

    echo "${_ver}" > "${APP_DIRECTORY}/version.id"

    CHOWN_DIR "${APACHE_USER}":"${APACHE_GROUP}" "${APP_DIRECTORY}" || break

    # -- Configure 'apache2' service
    _apache_conf="/etc/apache2/userconf-enabled/librespeed-${USERNAME}.conf"
    _password_file="/etc/apache2/users.password"
    if [ ! -d "/etc/apache2/userconf-enabled/" ] ; then
        MKDIR "/etc/apache2/userconf-enabled" || break
    fi
    if [ "${USERUID}" = "${FIRST_UID}" ] ; then
        _prefix="/librespeed"
    else
        _prefix="/librespeed-${USERNAME}"
    fi
    cat <<-EOF > "${_apache_conf}"
	RewriteEngine on
	RewriteRule ^${_prefix}$ ${_prefix}/ [R=permanent]
	Alias "${_prefix}" "${APP_DIRECTORY}/"
	<Location "${_prefix}">
	    Order deny,allow
	    Deny from all
	    Allow from all
	    AuthType Digest
	    AuthName "apache2"
	    AuthUserFile ${_password_file}
	    Require user ${USERNAME}
	</Location>
	EOF

    RUN_LOG "apachectl -t" || break
    SVC_RELOAD "${APACHE_SVC}"

    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}': Starting cleanup procedure"
    RM_DIRS "${APP_DIRECTORY}"
    if [ -e "/etc/apache2/userconf-enabled/librespeed-${USERNAME}.conf" ] ; then
        RM_FILES "/etc/apache2/userconf-enabled/librespeed-${USERNAME}.conf"
        SVC_RELOAD "${APACHE_SVC}"
    fi
fi

SCRIPTEXIT
