#
# CloudCredentials.R
#
# Copyright (C) 2023 by Posit Software, PBC
#
# Unless you have received this program directly from Posit Software pursuant
# to the terms of a commercial license agreement with Posit Software, then
# this program is licensed to you under the terms of version 3 of the
# GNU Affero General Public License. This program is distributed WITHOUT
# ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
# AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
#
#

.rs.addApiFunction("getDelegatedAzureToken", function(resource, ...) {
  result <- .Call("rs_invokeServerRpc", "/delegated_azure_token", resource)
  if (!is.null(result$oauth2_error)) {
    obj <- result$oauth2_error
    formatted <- paste(
      c(
        sprintf("OAuth failure: %s", obj$error),
        obj$error_description,
        if (obj$error_uri != "") sprintf("Learn more at <%s>", obj$error_uri),
        result$detail
      ),
      collapse = "\n"
    )
    stop(formatted, call. = FALSE)
  }
  if (result$result == FALSE) {
    stop(result$detail, call. = FALSE)
  }
  token <- result$token
  # Convert expiry from relative seconds to an actual timestamp so that the
  # caller doesn't lose this information when inspecting the token later.
  token$expires_at <- as.numeric(Sys.time()) + token$expires_in
  token$expires_in <- NULL
  token$ext_expires_in <- NULL
  token
})

.rs.addApiFunction("getSnowflakeToken",
                   function(account = Sys.getenv("SNOWFLAKE_ACCOUNT")) {
  if (nchar(account) == 0) {
    return(NULL)
  }
  # Check for a Workbench-managed Snowflake configuration file.
  if (!grepl("workbench", Sys.getenv("SNOWFLAKE_HOME"), fixed = TRUE)) {
    return(NULL)
  }
  cfg <- readLines(file.path(Sys.getenv("SNOWFLAKE_HOME"), "connections.toml"))
  # Check that the configuration actually applies to this account.
  if (!any(grepl(account, cfg, fixed = TRUE))) {
    return(NULL)
  }
  line <- grepl("token = ", cfg, fixed = TRUE)
  token <- gsub("token = ", "", cfg[line])
  if (nchar(token) == 0) {
    return(NULL)
  }
  # Drop enclosing quotes.
  gsub("\"", "", token)
})
