#
# Copyright (c) 2024, Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


# Returns the value of the specified config
#
# $1 name of the config
# $2 config file, default ${VAULT_SERVER_CONF_FILE}
get_properties_conf_value() {
  local conf_name=$1
  local conf_file=${2:-${VAULT_SERVER_CONF_FILE}}

  if ! [ -f "$conf_file" ]; then
    echo "$conf_file does not exists"
    exit 1
  fi

  local conf_value=$(cat $conf_file | grep -v '#' | sed -E -n "s/$conf_name=(.*)/\1/p")
  echo "$conf_value"
}

# Set the value of the config in the config file
#
# $1 name of the env var
# $2 value of the env var
# $3 env file, default ${VAULT_SERVER_CONF_FILE}
set_properties_conf_value() {
  local conf_name=$1
  local conf_value=$2
  local conf_file=${3:-${VAULT_SERVER_CONF_FILE}}

  if ! [ -f "$conf_file" ]; then
    echo "$conf_file does not exists"
    return
  fi

  sed -i'.tmp' -E "s/^($conf_name=).*/\1${conf_value}/" $conf_file

  # check if the replacement was successful
  cat $conf_file | grep -q "$conf_name="
  if [ $? -ne 0 ]; then
    echo "$conf_name=$conf_value" >> $conf_file
  fi
}

# $1 the string to be lowered
to_lower() {
  echo $1 | tr '[:upper:]' '[:lower:]'
}

# $1 config file path
# $2 j2 templates folder
# $3 venv dir
create_config_file_from_j2_template() {
  local config_file=$1
  local templates_dir=${2:-${VAULT_TEMPLATES_DIR}}
  local config_file_template="${templates_dir}/$(basename ${config_file}).j2"
  local venv_dir=${3:-${VENV_DIR}}

  if [ ! -x "${VENV_DIR}/bin/python" ]; then
    echo "ERROR: No python executable in venv ${VENV_DIR}"
    exit 1
  fi

  source "${venv_dir}"/bin/activate
  ${VENV_DIR}/bin/python -c 'import os, sys, jinja2; sys.stdout.write(jinja2.Template(sys.stdin.read()).render(env=os.environ))' <$config_file_template >$config_file

  deactivate
}


get_openssl_version() {
  openssl version -v | awk -F ' ' {'print $2'}
}

