#!/usr/bin/env bash
# bluesky-pds — install-steps hook (Phase 1d DG5).
#
# bluesky-pds's `pds_plc_rotation_key` secret is marked `generate=false` in the recipe (the PLC
# rotation key is a secp256k1 private key that the deploy WILL reject if not pre-inserted). Run
# this hook AFTER `abra app secret generate` (which handles the recipe's auto-gen secrets) and
# BEFORE `abra app deploy` — generate a fresh secp256k1 key + insert it.
#
# The key is per-run class-B (each per-run domain gets its own); destroyed with the app at run end.
#
# Environment supplied by the orchestrator:
#   CCCI_APP_DOMAIN — the per-run domain
#   CCCI_RECIPE     — "bluesky-pds"
#   CCCI_APP_ENV    — path to the app's .env file
set -euo pipefail
: "${CCCI_APP_DOMAIN:?CCCI_APP_DOMAIN must be set by the harness}"

echo "  bluesky-pds install_steps: generating secp256k1 PLC rotation key..."
# The recipe README's recipe uses openssl+xxd; cc-ci's PATH only has python3 (the nix
# cc-ci-run env). A random 32-byte value is overwhelmingly always a valid secp256k1 private key
# (P(invalid) ~= 2^-128); Python's secrets.token_bytes(32) is cryptographically random + the
# same shape the PDS expects (32-byte hex). Equivalent for atproto PDS bootstrap.
KEY_HEX=$(cc-ci-run -c 'import secrets; print(secrets.token_bytes(32).hex())')
if [ -z "${KEY_HEX}" ] || [ "${#KEY_HEX}" != "64" ]; then
  echo "  install_steps: failed to generate PLC rotation key (KEY_HEX length=${#KEY_HEX})" >&2
  exit 1
fi

# Insert via abra under TTY-wrap (`abra app secret insert` requires a TTY on this version).
# We DON'T log the key value — abra also doesn't print it.
script -qec "abra app secret insert ${CCCI_APP_DOMAIN} pds_plc_rotation_key v1 ${KEY_HEX} --no-input" /dev/null \
  >/dev/null 2>&1
echo "  bluesky-pds install_steps: PLC rotation key inserted (v1)."
