#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$SCRIPT_DIR/../config"
JWKS_FILE="$CONFIG_DIR/id_token.jwks.json"

# Check if JWKS file already has keys
if [ -f "$JWKS_FILE" ]; then
    KEY_COUNT=$(cat "$JWKS_FILE" | jq '.keys | length' 2>/dev/null || echo "0")
    if [ "$KEY_COUNT" -gt 0 ]; then
        echo "JWKS keys already exist at $JWKS_FILE"
        echo "If you want to regenerate, delete the file first."
        exit 0
    fi
fi

echo "Generating JWKS keys..."
docker run --rm oryd/oathkeeper:v0.40.9 credentials generate --alg RS256 > "$JWKS_FILE"

if [ $? -eq 0 ]; then
    echo "✓ JWKS keys successfully generated at $JWKS_FILE"
else
    echo "✗ Failed to generate JWKS keys"
    exit 1
fi
