# shellcheck shell=dash

___x_cmd_hub_access___decrypt_filekey_(){
    local remotefp="$1"
    [ -n "$remotefp" ] || M='Provide resource path' N=hub log:ret:64

    local res="$remotefp"
    # TODO res?
    local resp=
    resp="$(___x_cmd_hub_u_curl get /api/v0/filekey res==)"|| {
        if [ "$(___x_cmd_hub_u_curl_resp_code)" = 404 ];then
            hub:debug "No encrypted filekey for $remotefp"
            return 0
        fi

        ___x_cmd_hub_u_handle_resp false  "Failed to get filekey for $remotefp"
        return 1
    }

    local filekey_path=
    filekey_path="$(___x_cmd_hub_u_remote2localfp datakey "$remotefp")" || return 1
    x_=; ___x_cmd_hub_keypair_get_key_path_ "$___X_CMD_HUB_KEYPAIR_NAME" private || return 1
    printf "%s" "$resp" | ___x_cmd_hub_file___decrypt_filekey "$x_" > "$filekey_path" || {
        ___x_cmd_ui_tf false "Failed to decrypt filekey to $filekey_path" >&2
        return 1
    }
    x_="$filekey_path"
}

___x_cmd_hub_access___authorized_filekey_(){
    local user_list="$1"   ; [ -n "$user_list"    ] || M='Provide user_list'     N=hub log:ret:64
    local remotefp="$2"    ; [ -n "$remotefp"     ] || M='Provide resource path' N=hub log:ret:64
    local filekey_path="$3"; [ -n "$filekey_path" ] || M='Provide filekey path'  N=hub log:ret:64

    ___x_cmd_hub_keypair___download_pubkey_list "$user_list" || return 1

    x_=""
    user_list="${user_list},"

    local username=; local key_path=; local enc_filekey=
    while [ -n "${user_list%%,*}" ] ; do
        username="${user_list%%,*}"
        key_path="$___X_CMD_HUB_DATA/$username/keypair/default_public.pem"

        enc_filekey="$(< "$filekey_path" ___x_cmd_hub_file___encrypt_filekey "$key_path")" || {
            ___x_cmd_ui_tf false "Failed to encrypt filekey to $enc_filekey" >&2
            return 1
        }

        x_="${x_}{username:${username},filekey:${enc_filekey}},"
        user_list="${user_list#*,}"
    done
    x_="[${x_}]"
}

___x_cmd_hub_access___upload_filekey(){
    local filekey_date="$1"; [ -n "$filekey_date" ] || M='Provide filekey date'  N=hub log:ret:64
    local remotefp="$2"    ; [ -n "$remotefp"     ] || M='Provide resource path' N=hub log:ret:64

    filekey_date="$(printf "%s" "${filekey_date}" | ___x_cmd jo fmt)"
    local resp=
    resp="$(___x_cmd_hub_u_curl put "/api/v0/filekey/share?res=${remotefp}" filekey_date)" || {
        ___x_cmd_hub_u_handle_resp false "Failed to put filekey for $remotefp"
        return 1
    }
}
