#!/usr/bin/env bash
#
# Rotate the LiveKit API-Key + Secret and restart the SFU. Prints the new
# values so you can paste them into the Supabase Edge-Function env (the
# mint-livekit-token function signs JWTs with them).
#
# Usage:
#   ./scripts/prod/rotate-livekit-keys.sh

set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${here}/config.sh"

new_key="API$(openssl rand -hex 8)"
new_secret="$(openssl rand -hex 32)"

echo "new LiveKit credentials:"
echo "  LIVEKIT_API_KEY=${new_key}"
echo "  LIVEKIT_API_SECRET=${new_secret}"
echo
read -rp "write these into ${PROD_LIVEKIT_DIR}/livekit.yaml on the server? [y/N] " confirm
if [[ "${confirm,,}" != "y" ]]; then
  echo "aborted — nothing changed."
  exit 1
fi

# Replace the `keys:` block (last non-empty section in our config).
remote "cd ${PROD_LIVEKIT_DIR} && \
  python3 - <<'PY'
from pathlib import Path
p = Path('livekit.yaml')
lines = p.read_text().splitlines()
out = []
skip = False
for line in lines:
    if line.strip().startswith('keys:'):
        out.append('keys:')
        out.append(f'  ${new_key}: ${new_secret}')
        skip = True
        continue
    if skip:
        if line.startswith(' '):
            continue
        skip = False
    out.append(line)
p.write_text('\n'.join(out) + '\n')
print('livekit.yaml updated')
PY"

remote "cd ${PROD_LIVEKIT_DIR} && docker compose restart livekit"
echo
echo "LiveKit restarted with new keys."
echo
echo "Next: push these to the Supabase Edge-Function env on the server:"
echo "  edit ${PROD_SUPABASE_DIR}/.env  →  set LIVEKIT_API_KEY / LIVEKIT_API_SECRET"
echo "  then: ./scripts/prod/restart.sh supabase functions"
