#!/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:=}

# same as previous but with '.' replaced by '-'
export API_ORTHODB_VERSION_NODOT=${API_ORTHODB_VERSION_NODOT:=}

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

export ALLOWED_ORTHODB_API_VERSIONS=( current v11 v12 )
clean_url_api() {
    local ver=$1
    ver=${ver,,}
    # change v11.x to v11-x
    ver="${ver//./-}"

    # change v11-0 to v11
    ver="${ver//-0/}"
    
    #ver="${ver%%.*}"
    [[ "${ALLOWED_ORTHODB_API_VERSIONS[@]}" =~ "$ver" ]] || {
        # unknown version - fallback to current
        echo "current"
        return 1
    }
    echo "$ver"
    return 0
}

# 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=""

    # clean API
    URL_ORTHODB_API_VERSION=$(clean_url_api $URL_ORTHODB_API_VERSION)
    if [[ $? -ne 0 ]]; then
        echo "WARNING: unknown API version given - fall back to '$URL_ORTHODB_API_VERSION'"
    fi
    
    # 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"
    API_ORTHODB_VERSION_NODOT="${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
}

export -f clean_url_api
export -f set_orthodb_api
