#!/usr/bin/env bash
#
# 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.
#

SCRIPT_PATH="$(
  cd "$(dirname "$0")" >/dev/null 2>&1 || exit
  pwd -P
)"

VAULT_APP_DATA_DIR=${VAULT_APP_DATA_DIR:-${HOME}/.vault_data}


# if called as source code then return
[[ $_ != $0 ]] && return 2>/dev/null

VAULT_CONF_DIR=${VAULT_CONF_DIR:-${VAULT_APP_DATA_DIR}/conf}

if [ -n "${IN_VAULT_SERVER_PORT}" ]; then
  VAULT_SERVER_PORT=${IN_VAULT_SERVER_PORT}
fi

if [ -n "${IN_VAULT_SERVER_VERSION}" ]; then
  VAULT_SERVER_VERSION=${IN_VAULT_SERVER_VERSION}
fi

source "$SCRIPT_PATH"/common.sh # load commons
LOG_FILE="$LOGS_DIR"/$(basename "$0" .sh).log

# create vault-server.properties
if [ ! -f ${VAULT_SERVER_CONF_FILE} ]; then
  create_vault_server_conf
else
  backup_vault_server_conf

  changed=false
  if [ -n "${IN_VAULT_SERVER_PORT}" ]; then
    update_port "vault.server.port" "${VAULT_SERVER_PORT}" "${VAULT_SERVER_CONF_FILE}" $(get_vault_server_pid) | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
      changed=true
    fi
  fi

  if [ -n "${IN_VAULT_SERVER_VERSION}" ]; then
    update_config "vault.server.version" "${VAULT_SERVER_VERSION}" "${VAULT_SERVER_CONF_FILE}" | tee -a "$LOG_FILE"
    if [ ${PIPESTATUS[0]} -eq 0 ]; then
      changed=true
    fi
  fi

  if [ "$changed" = true ]; then
    echo "The change(s) will take effect after Vault Server is restarted!"
  else
    echo "Nothing is changed";
  fi
fi