#!/bin/bash
# BEMServer entrypoint - runs the specified component
set -e

COMPONENT=${BEMSERVER_COMPONENT:-api}
CONFIG_DIR="/opt/bemserver/config"

case "$COMPONENT" in
    api)
        echo "Starting BEMServer API on port 5000..."
        exec flask --app bemserver_api.app create --config "${CONFIG_DIR}/api-settings.py"
        ;;
    ui)
        echo "Starting BEMServer UI on port 5001..."
        exec flask --app bemserver_ui.app create --config "${CONFIG_DIR}/ui-settings.cfg"
        ;;
    celery-worker)
        echo "Starting BEMServer Celery worker..."
        export BEMSERVER_CORE_SETTINGS_FILE="${CONFIG_DIR}/core-settings.py"
        exec celery -A bemserver_core.celery_worker worker --loglevel=info
        ;;
    celery-beat)
        echo "Starting BEMServer Celery beat..."
        export BEMSERVER_CORE_SETTINGS_FILE="${CONFIG_DIR}/core-settings.py"
        exec celery -A bemserver_core.celery_worker beat --loglevel=info
        ;;
    init-db)
        echo "Initializing BEMServer database..."
        export BEMSERVER_CORE_SETTINGS_FILE="${CONFIG_DIR}/core-settings.py"
        bemserver_db_upgrade
        echo "Database initialized."
        ;;
    create-admin)
        echo "Creating admin user..."
        export BEMSERVER_CORE_SETTINGS_FILE="${CONFIG_DIR}/core-settings.py"
        bemserver_create_user --name "${BEMSERVER_ADMIN_USER:-admin}" --email "${BEMSERVER_ADMIN_EMAIL:-admin@digitribe.fr}" --admin
        echo "Admin user created."
        ;;
    *)
        echo "Unknown component: $COMPONENT"
        echo "Valid components: api, ui, celery-worker, celery-beat, init-db, create-admin"
        exit 1
        ;;
esac
