#!/bin/bash

SCRIPT_VER="1.4"

APP="Librespeed"
APP_CATEGORY="Utilities"
APP_SCOPE="system"
APP_ENABLED="yes"
STORED_PASSWORD_SERVICE="userdir"
#><#APP_CHECK_VER_CMD="[ -s "/var/www/librespeed/version.id" ] && cat "/var/www/librespeed/version.id" || echo """
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

APP_DIRECTORY="/var/www/librespeed"

while : ; do

    main_rc=1

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

    # -- Install required packages
    APT_INSTALL "php-sqlite3" "unzip" || break

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

    # -- Fetch and install the latest `librespeed/speedtest` package
    GITHUB_RELEASE "librespeed/speedtest" "latest" "" "" "^$" || break
    _ver="${GITHUB_RELEASE_TAG}"
    if [ -z "${_ver}" ] ; then
        ERROR "Could not determine ${APP} version!"
        break
    fi
    INFO "Latest build: ${_ver}"
    WGET "${GITHUB_RELEASE_ASSET_URL}" "${GITHUB_RELEASE_ASSET_NAME}" || break
    _archive_root="$( unzip -Z -1 "${TMP_DIR}/${GITHUB_RELEASE_ASSET_NAME}" 2>> "${LOGFILE}" \
                      | awk -F "/" 'NR == 1 {print $1}' )"
    if [ -z "${_archive_root}" ] ; then
        ERROR "Could not determine ${APP} archive root!"
        break
    fi
    UNZIP "${TMP_DIR}/${GITHUB_RELEASE_ASSET_NAME}" "${TMP_DIR}" || break
    _archive_dir="${TMP_DIR}/${_archive_root}"
    if [ -z "${_archive_dir}" ] || [ ! -d "${_archive_dir}" ] ; then
        ERROR "Could not determine ${APP} archive directory!"
        break
    fi
    RUN_LOG "cp -rpf \"${_archive_dir}/.\" \"${APP_DIRECTORY}/\"" || break

    if [ -e "${APP_DIRECTORY}/example-singleServer-gauges.html" ] ; then
        CP_FILE "${APP_DIRECTORY}/example-singleServer-gauges.html" \
                "${APP_DIRECTORY}/index.html" \
            || break
    elif [ -e "${APP_DIRECTORY}/examples/example-singleServer-gauges.html" ] ; then
        CP_FILE "${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\"" || break
    RUN_LOG "sed -i -e '/<a href=\"https:\/\/github.com\/librespeed.*<\/a>/d' \
                 \"${APP_DIRECTORY}/index.html\"" || break
    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 ] && [ "${main_rc}" -ne 111 ] && [ "${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
