#!/bin/bash
set -e

# Load secrets from Infisical and export to environment
echo "Loading secrets from Infisical..."
python -c "
import os
from infisical_sdk import InfisicalSDKClient

client = InfisicalSDKClient(host=os.environ['INFISICAL_API_URL'])
client.auth.universal_auth.login(
    client_id=os.environ['INFISICAL_CLIENT_ID'],
    client_secret=os.environ['INFISICAL_CLIENT_SECRET'],
)

env = os.environ.get('INFISICAL_ENV', 'prod')
project_id = os.environ['INFISICAL_PROJECT_ID']

for path in ['/prefect', '/shared']:
    secrets = client.secrets.list_secrets(
        environment_slug=env,
        secret_path=path,
        project_id=project_id,
        expand_secret_references=True,
        view_secret_value=True,
    )
    for secret in secrets.secrets:
        print(f'export {secret.secretKey}=\"{secret.secretValue}\"')
" > /tmp/secrets.sh

source /tmp/secrets.sh
rm /tmp/secrets.sh

echo "Starting Prefect services..."
exec prefect server services start
