#!/usr/bin/env bash
# Combined healthcheck for Vault container.
# Succeeds only if:
#  1. Vault sys/health endpoint indicates active (not standby)
#  2. CMA_VAULT_SERVER_ACCESS_FILE exists and contains non-empty role & secret IDs
# Optional: when SSL config file exists, use its cert for curl.

set -eo pipefail

get_cma_conf_value() {
  local conf_name=${1}
  local conf_file=${2}

  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}"
}

if [ -f "${CMA_VAULT_SERVER_CONF_FILE}" ]; then
  VAULT_SERVER_HOST=$(get_cma_conf_value "vault.server.host" "${CMA_VAULT_SERVER_CONF_FILE}")
  VAULT_SERVER_PORT=$(get_cma_conf_value "vault.server.port" "${CMA_VAULT_SERVER_CONF_FILE}")
  VAULT_SERVER_SCHEME=$(get_cma_conf_value "vault.server.scheme" "${CMA_VAULT_SERVER_CONF_FILE}")
fi

VAULT_ADDR="${VAULT_SERVER_SCHEME}://${VAULT_SERVER_HOST}:${VAULT_SERVER_PORT}"
echo "Vault address: ${VAULT_ADDR}"

# Health endpoint check
curl_opts=(--fail --silent --show-error)
if [ -f "$CMA_VAULT_SERVER_SSL_FILE" ]; then
  CERT_PEM=$(get_cma_conf_value "server.ssl.cert.pem" "$CMA_VAULT_SERVER_SSL_FILE" || true)
  if [ -n "$CERT_PEM" ] && [ -f "$CERT_PEM" ]; then
    curl_opts+=(--cacert "$CERT_PEM")
  else
    # If scheme is https but we lack cert, allow insecure to avoid false negatives
    if [ "$VAULT_SERVER_SCHEME" = "https" ]; then
      curl_opts+=(-k)
    fi
  fi
else
  # allow self-signed for dev if https without explicit ssl file
  if [ "$VAULT_SERVER_SCHEME" = "https" ]; then
    curl_opts+=(-k)
  fi
fi

health_json=""
if ! health_json=$(curl "${curl_opts[@]}" -X GET "$VAULT_ADDR/v1/sys/health" 2>/dev/null); then
  echo "Vault health endpoint not reachable" && exit 1
fi

# Accept active or (in dev) sealed=false + standby=false
if ! echo "$health_json" | grep -q '"standby":false'; then
  echo "Vault not active yet" && exit 1
fi

# Access file checks
if [ ! -f "$CMA_VAULT_SERVER_ACCESS_FILE" ]; then
  echo "Access file missing: $CMA_VAULT_SERVER_ACCESS_FILE" && exit 1
fi
ROLE_ID=$(get_cma_conf_value "vault.server.role.id" "$CMA_VAULT_SERVER_ACCESS_FILE")
SECRET_ID=$(get_cma_conf_value "vault.server.secret.id" "$CMA_VAULT_SERVER_ACCESS_FILE")
if [ -z "$ROLE_ID" ] || [ -z "$SECRET_ID" ]; then
  echo "RoleId/SecretId not populated yet" && exit 1
fi

echo "Vault health OK and access file ready"
exit 0
