#!/bin/sh
set -e

# Source vault secrets if available
if [ -f /vault/secrets/.env ]; then
    echo "Loading secrets from Vault..."
    export $(grep -v '^#' /vault/secrets/.env | xargs)
fi

echo "Processing Oathkeeper configuration templates..."

# Substitute environment variables in oathkeeper.yml
envsubst < /etc/oathkeeper/oathkeeper.yml.template > /etc/oathkeeper/oathkeeper.yml
echo "✓ Processed oathkeeper.yml"

# Create rules directory and process templates
mkdir -p /etc/oathkeeper/rules
for template in /etc/oathkeeper/rules.template/*.yml; do
    filename=$(basename "$template")
    envsubst < "$template" > "/etc/oathkeeper/rules/$filename"
    echo "✓ Processed rules/$filename"
done

# Set proper ownership
chown -R ory:ory /etc/oathkeeper

echo "Starting Oathkeeper as ory user..."
exec su-exec ory oathkeeper "$@"
