#!/bin/bash
set -e

# Oclawma Docker Entrypoint Script
# Handles initialization and graceful shutdown

# Signal handlers for graceful shutdown
cleanup() {
    echo "Received shutdown signal, cleaning up..."
    # Give the application time to shut down gracefully
    if [ -n "$PID" ]; then
        kill -TERM "$PID" 2>/dev/null || true
        wait "$PID" 2>/dev/null || true
    fi
    echo "Shutdown complete."
    exit 0
}

# Trap SIGTERM and SIGINT for graceful shutdown
trap cleanup SIGTERM SIGINT

# Ensure data directories exist
mkdir -p /app/data/config
mkdir -p /app/data/logs
mkdir -p /app/data/sessions

# Set up config directory if not exists
if [ ! -f /app/data/config/settings.yaml ]; then
    echo "Initializing default configuration..."
    oclawma config init --path /app/data/config/settings.yaml || true
fi

# Run health check once to verify installation
echo "Verifying Oclawma installation..."
oclawma --version

echo "Oclawma ready."

# If no arguments provided, show help
if [ $# -eq 0 ]; then
    set -- oclawma --help
fi

# If first argument is 'oclawma', run it directly
if [ "$1" = "oclawma" ]; then
    exec "$@"
else
    # Otherwise, prepend 'oclawma' to arguments
    exec oclawma "$@"
fi
