#!/bin/bash

VAULT_TOKEN_FILE="${VAULT_TOKEN_FILE:-${HOME}/.vault-token.json}"
CMA_PYTHON_EXECUTABLE=${CMA_PYTHON_EXECUTABLE:-python3}
INTERVAL=1   # check every 1 second
ROLE="${ROLE:-auth/approle/role/cma-role}"
POLICY="${POLICY:-cma-policy}"


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


args=(-vsc="${CMA_VAULT_SERVER_CONF_FILE}")
[ -f "${CMA_VAULT_SERVER_SSL_FILE}" ] && args+=(-ssc="${CMA_VAULT_SERVER_SSL_FILE}")

"${CMA_HOME}/vault-local/scripts/bin/vault-server.sh" start "${args[@]}"

echo "Waiting for vault token file: ${VAULT_TOKEN_FILE}..."

while [ ! -f "${VAULT_TOKEN_FILE}" ]; do
  sleep $INTERVAL
done

echo "Vault token file found: ${VAULT_TOKEN_FILE}"
cp -r "${VAULT_TOKEN_FILE}" "${CMA_CONTAINER_INSTANCE_DIR}/conf/"

VAULT_TOKEN=$(cat ${VAULT_TOKEN_FILE} | ${CMA_PYTHON_EXECUTABLE} -c "import sys, json; print(json.load(sys.stdin)['root_token'])")
[ -f "${CMA_VAULT_SERVER_SSL_FILE}" ] && VAULT_CACERT=$(get_cma_conf_value "server.ssl.cert.pem" "${CMA_VAULT_SERVER_SSL_FILE}")

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 "Enabling vault authentication..."
echo "Vault address: ${VAULT_ADDR}"

curl_opts=""
[ -n "$VAULT_CACERT" ] && curl_opts="--cacert $VAULT_CACERT"

# Enable AppRole auth method using HTTP API
if ! curl $curl_opts -s -X POST \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  -H "Content-Type: application/json" \
  --data "{\"type\": \"approle\"}" \
  "$VAULT_ADDR/v1/sys/auth/approle"; then
  echo "Failed to enable approle auth method"
  exit 1
fi

# Create policy
policy_payload="{\"policy\": \"path \\\"*\\\" {\\n  capabilities = [\\\"create\\\", \\\"read\\\", \\\"update\\\", \\\"delete\\\", \\\"list\\\", \\\"sudo\\\"]\\n}\"}"
if ! curl $curl_opts -s -X PUT \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  -H "Content-Type: application/json" \
  --data "$policy_payload" \
  "$VAULT_ADDR/v1/sys/policies/acl/$POLICY"; then
  echo "Failed to create policy"
  exit 1
fi

# Create role
if ! curl $curl_opts -s -X POST \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  -H "Content-Type: application/json" \
  --data "{\"token_policies\": [\"$POLICY\"]}" \
  "$VAULT_ADDR/v1/$ROLE"; then
  echo "Failed to create role"
  exit 1
fi

# Get role ID
if ! role_id_response=$(curl $curl_opts -s -X GET \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  "$VAULT_ADDR/v1/$ROLE/role-id"); then
  echo "Failed to get role ID"
  exit 1
fi
if [[ "$role_id_response" == *"\"errors\":"* ]]; then
  echo "Failed to get role ID"
  echo "Response: ${role_id_response}"
  exit 1
fi

CMA_VAULT_ROLE_ID=$(echo "$role_id_response" | ${CMA_PYTHON_EXECUTABLE} -c "import sys, json; print(json.load(sys.stdin)['data']['role_id'])")

# Get secret ID
if ! secret_id_response=$(curl $curl_opts -s -X POST \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  "$VAULT_ADDR/v1/$ROLE/secret-id"); then
  echo "Failed to get secret ID"
  exit 1
fi
if [[ "$secret_id_response" == *"\"errors\":"* ]]; then
  echo "Failed to get secret ID"
  echo "Response: ${secret_id_response}"
  exit 1
fi

CMA_VAULT_SECRET_ID=$(echo "$secret_id_response" | ${CMA_PYTHON_EXECUTABLE} -c "import sys, json; print(json.load(sys.stdin)['data']['secret_id'])")

if [ -z "${CMA_VAULT_ROLE_ID}" ] || [ -z "${CMA_VAULT_SECRET_ID}" ]; then
  echo "Failed to enable vault authentication: CMA_VAULT_ROLE_ID or CMA_VAULT_SECRET_ID is empty!" | tee -a "$LOG_FILE"
  exit 1
fi

echo "Vault authentication is enabled successfully."

echo 'Create cma-vault-access.properties ...'
cat >"${CMA_VAULT_SERVER_ACCESS_FILE}" <<EOF
# vault server access
vault.server.role.id=${CMA_VAULT_ROLE_ID}
vault.server.secret.id=${CMA_VAULT_SECRET_ID}
EOF

# secure config file
chmod 600 "${CMA_VAULT_SERVER_ACCESS_FILE}"

# process running to keep the container alive
tail -f /dev/null
