#!/usr/bin/env bash

# URL for OrthoDB API - user settable
export URL_ORTHODB_API_BASE=${URL_ORTHODB_API_BASE:="https://data.orthodb.org"}
export URL_ORTHODB_API_VERSION=${URL_ORTHODB_API_VERSION:="current"}

#-----------------------------------------------
# Deduced by the above, see set_orthodb_api()
# Note that they may have been already set before!

# Full APU url
export URL_ORTHODB_API=${URL_ORTHODB_API:=}

# OrthoDB version string as retrieved from API
export API_ORTHODB_VERSION=${API_ORTHODB_VERSION:=}

# OrthoDB version string used with mapping (e.g odb11v0 for v11)
export MAP_ORTHODB_VERSION=${MAP_ORTHODB_VERSION:=}

# Set OrthoDB API URL's.
# In addition retrieve API version string.
set_orthodb_api() {
    # mapping odb version string - part of filenames to be downloaded
    MAP_ORTHODB_VERSION=""

    # set full API url
    URL_ORTHODB_API=$URL_ORTHODB_API_BASE/$URL_ORTHODB_API_VERSION

    # get API orthodb version string
    local url="$URL_ORTHODB_API/orthodb_release_id"
    local odbver=$(curl -H "Accept: text/plain" --silent $url 2>/dev/null)
    # it returns plain text OrthoDB version
    API_ORTHODB_VERSION="$odbver"
    if [[ $odbver == "v11.0" ]]; then
        MAP_ORTHODB_VERSION="odb11v0"
        URL_ORTHODB_API_VERSION="v11"
    elif [[ $odbver == "v12.0" ]]; then
        MAP_ORTHODB_VERSION="odb12v0"
        URL_ORTHODB_API_VERSION="v12"
    else
        if [[ -n $odbver ]]; then
            echo "URL for OrthoDB API returns an invalid version id"
            echo "URL: $url"
            echo "Version id -> $odbver"
            return 255
        else
            echo "Failed accessing OrthoDB API."
            echo "URL: $url"
            echo "Mapping against OrthoDB data may fail if data is not already downloaded."
        fi
    fi
    # reset API url
    URL_ORTHODB_API=$URL_ORTHODB_API_BASE/$URL_ORTHODB_API_VERSION
    #echo "API version     : $API_ORTHODB_VERSION"
    #echo "API url         : $URL_ORTHODB_API"
    return 0
}

