. /usr/lib/yandex/maps/ecstatic-support/switchlib.sh

function check_alive() {
    host=$1
    curl --fail --silent --max-time 5 -H "Host: ${host}" "http://localhost/ping"
}


function switch_datasets() {
    service=$1
    host=$2
    version=$3
    local -n array=$4
    running_count=$(sudo -n yacare status ${service} | grep "is running" | wc -l)
    ping_status=$(curl -o /dev/null -s -w "%{http_code}" -H "Host: ${host}" "http://localhost/ping")

    if areRequiredDatasetsAvailable ; then
        if [ ${running_count} == 1 ] && [ ${ping_status} == 200 ]; then
            for dataset in "${!array[@]}"; do
                path=${array[${dataset}]}
                if [ -z "${version}" ]; then
                    echo "Switching dataset ${dataset} to empty version"
                    curl --fail --silent --max-time 5 -X POST \
                        -H "Host: ${host}" "http://localhost/service/reload_dataset?dataset=${dataset}"
                else
                    dest_path=`readlink -f ${path}`
                    echo "Switching dataset ${dataset} to ${dest_path}"
                    curl --fail --silent --max-time 5 -X POST \
                        -H "Host: ${host}" "http://localhost/service/reload_dataset?dataset=${dataset}&path=${dest_path}"
                fi
            done
        else
            sudo -n yacare stop ${service}
            nohup sudo -n yacare start ${service} &>/dev/null &
        fi
    else
        sudo -n yacare stop ${service}
    fi
    echo "Done"
}
