#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
ENV_FILE="${ROOT_DIR}/.env"
COMPOSE_FILE="${ROOT_DIR}/docker-compose.node2-sofiia.yml"

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "Missing .env: ${ENV_FILE}" >&2
  exit 1
fi

NEW_KEY="$(openssl rand -hex 24)"

if grep -q '^SOFIIA_CONSOLE_API_KEY=' "${ENV_FILE}"; then
  sed -i '' "s/^SOFIIA_CONSOLE_API_KEY=.*/SOFIIA_CONSOLE_API_KEY=${NEW_KEY}/" "${ENV_FILE}"
else
  printf '\nSOFIIA_CONSOLE_API_KEY=%s\n' "${NEW_KEY}" >> "${ENV_FILE}"
fi

if grep -q '^SUPERVISOR_API_KEY=' "${ENV_FILE}"; then
  sed -i '' "s/^SUPERVISOR_API_KEY=.*/SUPERVISOR_API_KEY=${NEW_KEY}/" "${ENV_FILE}"
else
  printf 'SUPERVISOR_API_KEY=%s\n' "${NEW_KEY}" >> "${ENV_FILE}"
fi

docker compose -f "${COMPOSE_FILE}" up -d sofiia-console router >/dev/null

echo "Sofiia keys rotated and services restarted."
echo "Use this API key for X-API-Key header:"
echo "${NEW_KEY}"
