#!/usr/bin/env bash
# set -x
declare -A onezones

onezones=(\
    [datahub]="datahub.egi.eu"
    [org]="onedata.org"
    [beta]="beta.onedata.org"
    [hnsc]="onedata.hnsc.otc-service.com"
    [wgs]="oz3-wg.tk"
    [pl]="onedata.plgrid.pl"
)

main() {
    local zone=$1
    local space_name=$2
    local token=$3
    local import=$4

    _curl=(curl --fail --silent -k "$curl_auth")

    if ! [[ ${onezones[$zone]} != "" ]] ; then
        echo "There is no Onezone for key: $zone"
        echo "Please use on of those:"
        for zone in "${!onezones[@]}"; do   # Enumerate all indices (user names)
            #if ! a_version=$(${_curl[@]} "https://${onezones[$zone]}/version" 2>/dev/null); then
            if ! a_version=$(${_curl[@]} "https://${onezones[$zone]}/configuration" | tr ',' '\n' | grep version | tr -d '"' | cut -d ':' -f 2 2>/dev/null); then
                a_version="error getting version"
            fi
            printf 'key:%s url:%s version:%s \n' "$zone" "${onezones[$zone]}" "$a_version"
        done
        exit 1
    fi
    local onezone_url="https://${onezones[$zone]}"

    if [[ "$import" == "" ]] ; then
        import="noimport"
    else
        import=""
    fi

    ###
    # Set access credentials
    ##
    if [[ "$token" == "" ]] ; then
        zone_token="${zone}_token"
        if [[ "${!zone_token}" != "" ]]; then
            token="${!zone_token}"
            curl_auth=" -H X-Auth-Token:${!$token}"
        else 
            zone_username="${zone}_username"
            zone_password="${zone}_password"
            if [[ "${!zone_password}" != "" ]] && [[ "${!zone_username}" != "" ]]; then
                zone_username="${!zone_password}"
                zone_password="${!zone_password}"
            else
                zone_username="admin"
                zone_password="password"
            fi
            curl_auth="-u $zone_username:$zone_password"
        fi
    else
        curl_auth=" -H X-Auth-Token:${token}"
    fi
        _curl+=("$curl_auth")

    ###
    # Try to match find matching space id
    ##
    if ! json_all_spaces=$(${_curl[@]} "$onezone_url/api/v3/onezone/user/spaces" 2>/dev/null); then
        echo "Error while getting list of spaces."
        exit 1
    else
        all_spaces=$(echo "$json_all_spaces" | jq -r '.spaces[]')
    fi

    matched_spaces=()
    not_matched_spaces=()
    for space_id in $all_spaces ; do
        if ! json_a_space_name=$(${_curl[@]} "$onezone_url/api/v3/onezone/spaces/$space_id"); then
            echo "Error while getting name of space "
            exit 1
        else
            a_space_name=$(echo "$json_a_space_name" | jq -r ".name")
        fi
        
        if [[ "$space_name" == "$a_space_name" ]]; then
            matched_spaces+=($a_space_name $space_id)
        else
            not_matched_spaces+=($a_space_name $space_id)
    fi
    done

    if [[ ${#matched_spaces[@]} -eq 0 ]]; then 
        echo "No space with name <$space_name> found in onezone <$onezone_url>".
        echo "Available spaces:"
        for (( i = 0; i < ${#not_matched_spaces[@]}; i += 2 )); do
            printf 'Space name: <%s> , space id: <%s>\n' "${not_matched_spaces[i]}" "${not_matched_spaces[i+1]}"
        done
        exit 1
    fi

    if [[ ${#matched_spaces[@]} -ge 3 ]]; then 
        echo "Found 2 or more spaces with name <$space_name> found in onezone <$onezone_url>:"
        for (( i = 0; i < ${#matched_spaces[@]}; i += 2 )); do
            printf 'Space name: <%s> , space id: <%s>\n' "${matched_spaces[i]}" "${matched_spaces[i+1]}"
        done
        echo "Cannot decide which one to use. Exiting."
        exit 1
    fi
    space_id=${matched_spaces[1]}

    [[ ! -z ${TEST_ONEDATIFY_CLEAN+x} ]] && _clean

    ###
    # Run Onedatify
    ##
    _test "$onezone_url" "$space_id" "$import"

}

_clean() {
    echo "Removing oneprovider container and direcotry /opt/onedata/onedatify"
    sudo docker rm -f onedatify-oneprovider-1 >/dev/null 2>&1
    sudo rm -rf /opt/onedata/onedatify
}

_test() {
    local onezone_url=$1
    local space_id=$2
    local import=$3
    script_url="https://get.onedata.org/onedatify.sh"
    ${_curl[@]} "$script_url" 2>/dev/null | \
    sh -s "$onezone_url" \
    $(${_curl[@]} \
           -H 'Content-type: application/json' \
           -X POST \
           "$onezone_url/api/v3/onezone/spaces/${space_id}/providers/token" \
           2>/dev/null \
            | jq -r .token \
    ) "$import"
}
# parse_command_line_options
# wrapped up in a function so that we have some protection against only getting
# half the file during "curl | sh"
main "$@"