#!/bin/bash

# SPADE startup script
# This script starts SPADE with RabbitMQ collector configuration

set -e

echo "Starting SPADE..."

# Set SPADE configuration directory
SPADE_CONFIG_DIR="/opt/SPADE/config"
SPADE_BIN_DIR="/opt/SPADE/bin"

# Create config directory if it doesn't exist
mkdir -p "$SPADE_CONFIG_DIR"

# Create a basic SPADE configuration file
cat > "$SPADE_CONFIG_DIR/spade.config" << EOF
# SPADE Configuration
# RabbitMQ Collector Configuration

# Enable RabbitMQ collector
rabbitmq.enabled=true
rabbitmq.host=rabbitmq
rabbitmq.port=5672
rabbitmq.username=guest
rabbitmq.password=guest
rabbitmq.queue=spade_events

# Enable basic collectors
collector.audit.enabled=true
collector.proc.enabled=true
collector.network.enabled=true

# Logging configuration
logging.level=INFO
logging.file=/opt/SPADE/logs/spade.log

# Output configuration
output.format=json
output.file=/opt/SPADE/output/spade_output.json
EOF

# Create necessary directories
mkdir -p /opt/SPADE/logs
mkdir -p /opt/SPADE/output

# Start SPADE in the background
echo "Starting SPADE with configuration..."
cd /opt/SPADE

# Check if SPADE binary exists
if [ -f "$SPADE_BIN_DIR/spade" ]; then
    echo "Found SPADE binary at $SPADE_BIN_DIR/spade"
    # Start SPADE with configuration
    "$SPADE_BIN_DIR/spade" start --config "$SPADE_CONFIG_DIR/spade.config" &
    SPADE_PID=$!
    echo "SPADE started with PID: $SPADE_PID"
    
    # Wait a moment for SPADE to start
    sleep 5
    
    # Check if SPADE is running
    if kill -0 $SPADE_PID 2>/dev/null; then
        echo "SPADE is running successfully"
        echo "SPADE PID: $SPADE_PID" > /opt/SPADE/spade.pid
    else
        echo "Failed to start SPADE"
        exit 1
    fi
else
    echo "SPADE binary not found at $SPADE_BIN_DIR/spade"
    echo "Available files in /opt/SPADE:"
    find /opt/SPADE -type f -name "spade" 2>/dev/null || echo "No spade binary found"
    exit 1
fi

echo "SPADE startup complete"
echo "Configuration file: $SPADE_CONFIG_DIR/spade.config"
echo "Log file: /opt/SPADE/logs/spade.log"
echo "Output file: /opt/SPADE/output/spade_output.json"

# Keep the container running
tail -f /opt/SPADE/logs/spade.log





















