#
# SessionDatabricks.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("getDatabricksToken", function(host = Sys.getenv("DATABRICKS_HOST"))
{
   if (nchar(host) == 0)
   {
      return(NULL)
   }
   # Check for a Workbench-managed Databricks configuration file.
   if (!grepl("workbench", Sys.getenv("DATABRICKS_CONFIG_FILE"), fixed = TRUE))
   {
      return(NULL)
   }
   cfg <- readLines(Sys.getenv("DATABRICKS_CONFIG_FILE"))
   # Check that the configuration actually applies to this host.
   if (!any(grepl(host, cfg, fixed = TRUE)))
   {
      return(NULL)
   }
   line <- grepl("token = ", cfg, fixed = TRUE)
   token <- gsub("token = ", "", cfg[line])
   if (nchar(token) == 0)
   {
      return(NULL)
   }
   token
})
