#!/bin/bash

set -e

scripts/verify_sauceconnect_env_ready.sh

# Global values for SauceLabs' sauceconnect utility
sc_version="4.4.2"
sc_fqn="sc-${sc_version}-linux"
sc_download_url="https://saucelabs.com/downloads/${sc_fqn}.tar.gz"
sc_checksum="57a07a14c5d95d72b6606ba34fceaf5bf76c2865"

# Create saucelabs directory if it doesn't exist.
if [ ! -d ".saucelabs" ];
then
    echo "Creating .saucelabs folder." >&2
    mkdir ".saucelabs"
fi

# Download the sauceconnect binary if not present.
sc_binary=".saucelabs/${sc_fqn}/bin/sc"
if [ ! -x "${sc_binary}" ];
then
    echo "Dowloading sauceconnect..." >&2
    sc_tar_file=".saucelabs/${sc_fqn}.tar.gz"

    curl "${sc_download_url}" -# -o "${sc_tar_file}"
    echo "Checking checksum of ${sc_tar_file}" >&2
    echo "${sc_checksum} ${sc_tar_file}" | sha1sum --check -
    echo "Extracting ${sc_tar_file}..." >&2
    tar -xzf "${sc_tar_file}" -C ".saucelabs"
fi

echo "Starting SauceConnect tunnel" >&2
"${sc_binary}" --user "${SAUCE_USERNAME}" --api-key "${SAUCE_ACCESS_KEY}" --readyfile ".saucelabs/sauce_is_ready" >&2
