#!/bin/bash

SCRIPT_VER="1.2"

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 """
#><#APP_UPGRADE_VER_CMD="curl -Ls --connect-timeout 10 --retry 3 -m 30 -o /dev/null -w "%{url_effective}" https://github.com/librespeed/speedtest/releases/latest | awk -F "/" "{print \$NF}""
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"
_stage_dir=""
_old_dir=""

while : ; do

    main_rc=1

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

    APT_INSTALL "php-sqlite3" "unzip" || break

    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

    _stage_dir="${TMP_DIR}/librespeed-stage"
    _old_dir="${TMP_DIR}/librespeed-old"
    MKDIR "${_stage_dir}" || break
    RUN_LOG "cp -rpf \"${_archive_dir}/.\" \"${_stage_dir}/\"" || break

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

    if [ -e "${APP_DIRECTORY}/speedtest_telemetry.sql" ] ; then
        CP_FILE "${APP_DIRECTORY}/speedtest_telemetry.sql" \
                "${_stage_dir}/speedtest_telemetry.sql" \
            || break
    fi
    if [ -e "${APP_DIRECTORY}/speedtest_telemetry.db" ] ; then
        CP_FILE "${APP_DIRECTORY}/speedtest_telemetry.db" \
                "${_stage_dir}/speedtest_telemetry.db" \
            || break
    fi

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

    if [ -d "${APP_DIRECTORY}" ] ; then
        MV "${APP_DIRECTORY}" "${_old_dir}" || break
    fi
    if ! MV "${_stage_dir}" "${APP_DIRECTORY}" ; then
        if [ -d "${_old_dir}" ] ; then
            MV "${_old_dir}" "${APP_DIRECTORY}"
        fi
        break
    fi
    if [ -d "${_old_dir}" ] ; then
        RM_DIRS "${_old_dir}"
    fi

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

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

    main_rc=0
    break

done


# Cleanup staged files if error
if [ "${main_rc}" -ne 0 ] && [ "${main_rc}" -ne 111 ] && [ "${main_rc}" -ne 117 ] ; then
    ERROR "'${APP}': Starting cleanup procedure"
    if [ -n "${_stage_dir}" ] && [ -d "${_stage_dir}" ] ; then
        RM_DIRS "${_stage_dir}"
    fi
    if [ -n "${_old_dir}" ] && [ -d "${_old_dir}" ] && [ ! -d "${APP_DIRECTORY}" ] ; then
        MV "${_old_dir}" "${APP_DIRECTORY}"
    fi
fi

SCRIPTEXIT
