Files
Qortal-Nextcloud-Integration/scripts/ensure-broker-internal-token.sh
2026-02-13 18:48:13 -08:00

71 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
env_file="${1:-.env.devprod}"
if [[ ! -f "${env_file}" ]]; then
echo "Missing env file: ${env_file}"
exit 1
fi
set_kv() {
local key="$1"
local value="$2"
local esc
esc="${value//\\/\\\\}"
esc="${esc//&/\\&}"
esc="${esc//|/\\|}"
if grep -q "^${key}=" "${env_file}"; then
sed -i -E "s|^${key}=.*|${key}=${esc}|" "${env_file}"
else
echo "${key}=${value}" >> "${env_file}"
fi
}
read_kv() {
local key="$1"
local line
line="$(grep -m1 -E "^${key}=" "${env_file}" || true)"
if [[ -z "${line}" ]]; then
return 1
fi
echo "${line#*=}"
}
existing_token="$(read_kv "BROKER_INTERNAL_API_TOKEN" || true)"
if [[ -n "${existing_token}" ]]; then
echo "Using existing broker internal API token from ${env_file}"
else
generated_token=""
if command -v openssl >/dev/null 2>&1; then
generated_token="$(openssl rand -hex 32)"
fi
if [[ -z "${generated_token}" ]]; then
generated_token="$(tr -dc 'a-zA-Z0-9' </dev/urandom | head -c 64)"
fi
set_kv "BROKER_INTERNAL_API_TOKEN" "${generated_token}"
echo "Generated BROKER_INTERNAL_API_TOKEN in ${env_file}"
fi
existing_cors_origins="$(read_kv "BROKER_CORS_ALLOWED_ORIGINS" || true)"
if [[ -z "${existing_cors_origins}" ]]; then
nextcloud_public_url="$(read_kv "NEXTCLOUD_PUBLIC_URL" || true)"
if [[ -n "${nextcloud_public_url}" ]]; then
set_kv "BROKER_CORS_ALLOWED_ORIGINS" "${nextcloud_public_url}"
echo "Set BROKER_CORS_ALLOWED_ORIGINS=${nextcloud_public_url} in ${env_file}"
fi
fi
final_token="$(read_kv "BROKER_INTERNAL_API_TOKEN" || true)"
if [[ -z "${final_token}" ]]; then
echo "Failed to set BROKER_INTERNAL_API_TOKEN in ${env_file}"
exit 1
fi
final_cors_origins="$(read_kv "BROKER_CORS_ALLOWED_ORIGINS" || true)"
if [[ -z "${final_cors_origins}" ]]; then
echo "BROKER_CORS_ALLOWED_ORIGINS is still empty in ${env_file}"
echo "Set NEXTCLOUD_PUBLIC_URL first, or set BROKER_CORS_ALLOWED_ORIGINS manually."
fi