#!/bin/sh

if [ "$(id -u)" != "0" ]
then
    echo "Manager must be run under root or with sudo"
    exit 1
fi

download_tools_manager(){ # addr, path_to_save

    ADDR=${1}  # URL without schema
    PATH_TO_SAVE=${2}

    HTTPS_URL="https://${ADDR}"
    HTTP_URL="http://${ADDR}"

    wget > /dev/null 2>&1
    CHECK_WGET=${?}
    curl > /dev/null 2>&1
    CHECK_CURL=${?}

    if [ "${CHECK_WGET}" != "127" ]
    then
        DOWNLOADER="wget"
    elif [ "${CHECK_CURL}" != "127" ]
    then
        DOWNLOADER="curl"
    else
        echo "Neither wget nor curl are not available"
        exit 1
    fi

    if [ "${DOWNLOADER}" = "wget" ]
    then
        WGET_OPTS="-q --no-check-certificate"
        wget ${WGET_OPTS} ${HTTPS_URL} -O "${PATH_TO_SAVE}"

        if [ ! -s "${PATH_TO_SAVE}" ]
        then
            # on old linuxes there is old openssl installed that doesn't support TLSv1 ciphers we use on our CDN
            wget ${WGET_OPTS} ${HTTP_URL} -O "${PATH_TO_SAVE}"
        fi

    elif [ "${DOWNLOADER}" = "curl" ]
    then
        CURL_OPTS="-s"
        curl ${HTTPS_URL} -o "${PATH_TO_SAVE}" "${CURL_OPTS}"

        if [ ! -s "${PATH_TO_SAVE}" ]
        then
            # on old linuxes there is old openssl installed that doesn't support TLSv1 ciphers we use on our CDN
            curl ${HTTP_URL} -o "${PATH_TO_SAVE}" "${CURL_OPTS}"
        fi
    else
        echo "Neither wget nor curl not available"
        exit 1
    fi
}

ADDR=download-cdn.resilio.com/debug-tools-repository/linux/rsl-pm
ADDR_MIRROR=d1jjr1neebnxgs.cloudfront.net/debug-tools-repository/linux/rsl-pm
BINARY_PATH=/bin/rsl-pm

# remove old version of package manager
rm -rf ${BINARY_PATH}

# Download form main CDN
download_tools_manager ${ADDR} ${BINARY_PATH}
if [ ! -s "${BINARY_PATH}" ]
then
    # Download from secondary CDN
    download_tools_manager ${ADDR_MIRROR} ${BINARY_PATH}
fi

if [ ! -s "${BINARY_PATH}" ]
then
    echo "Failed to download tools manager. Check if access to ${URL} and ${URL_MIRROR} is not blocked"
    exit 1
else
    chmod +x ${BINARY_PATH}
    echo "Tools manager has been installed. Run rsl-pm help"
    exit 0
fi
