#!/usr/bin/env bash
# generate-jwt-secret.sh — Generate a BA_AUTHD_JWT_SECRET and append
# it to .env (or print to stdout if --print).
#
# Usage:
#   scripts/generate-jwt-secret.sh           # appends/writes .env
#   scripts/generate-jwt-secret.sh --print   # prints to stdout only
#
# In docker-compose the secret is read via ${BA_AUTHD_JWT_SECRET:?}
# (required), so a fresh checkout won't start until you run this.
# The generated secret is 48 random bytes encoded as base64 (= 64
# chars, well above the 32-byte minimum).
#
# Idempotent: if .env already has a non-empty value, the script
# does nothing (use --force to overwrite).

set -euo pipefail

ENV_FILE="$(dirname "$0")/../.env"
PRINT_ONLY=0
FORCE=0
for arg in "$@"; do
  case "$arg" in
    --print) PRINT_ONLY=1 ;;
    --force) FORCE=1 ;;
    -h|--help)
      echo "usage: $0 [--print] [--force]" >&2
      exit 0
      ;;
  esac
done

# Read existing value if .env exists
existing=""
if [[ -f "$ENV_FILE" ]]; then
  existing=$(grep -E '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE" | tail -1 | cut -d= -f2- || true)
fi

if [[ -n "$existing" && $FORCE -eq 0 ]]; then
  if [[ $PRINT_ONLY -eq 1 ]]; then
    echo "$existing"
  else
    echo "BA_AUTHD_JWT_SECRET already set in $ENV_FILE (use --force to overwrite)"
  fi
  exit 0
fi

# 48 random bytes = 64 base64 chars. Plenty for HS256.
new_secret=$(openssl rand -base64 48)

if [[ $PRINT_ONLY -eq 1 ]]; then
  echo "$new_secret"
  exit 0
fi

# Write/append to .env
if [[ ! -f "$ENV_FILE" ]]; then
  # Start from .env.example if present
  if [[ -f "${ENV_FILE}.example" ]]; then
    cp "${ENV_FILE}.example" "$ENV_FILE"
  else
    touch "$ENV_FILE"
  fi
fi

if grep -qE '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE"; then
  # Replace existing line
  tmp=$(mktemp)
  grep -vE '^BA_AUTHD_JWT_SECRET=' "$ENV_FILE" > "$tmp"
  echo "BA_AUTHD_JWT_SECRET=$new_secret" >> "$tmp"
  mv "$tmp" "$ENV_FILE"
  echo "updated BA_AUTHD_JWT_SECRET in $ENV_FILE"
else
  # Append
  echo "" >> "$ENV_FILE"
  echo "# Generated by scripts/generate-jwt-secret.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$ENV_FILE"
  echo "BA_AUTHD_JWT_SECRET=$new_secret" >> "$ENV_FILE"
  echo "appended BA_AUTHD_JWT_SECRET to $ENV_FILE"
fi

echo ""
echo "next steps:"
echo "  1. docker compose up -d authd     # starts the IdP"
echo "  2. bash scripts/m13a_smoke.sh     # end-to-end smoke"
