#!/bin/bash
# Setup Logging Infrastructure
# This script ensures the logging system is properly configured after deployment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$(dirname "$SCRIPT_DIR")"
LOGS_DIR="$BACKEND_DIR/logs"

echo "🔧 Setting up logging infrastructure"
echo "===================================="
echo "Backend directory: $BACKEND_DIR"
echo "Logs directory: $LOGS_DIR"

# Create logs directory if it doesn't exist
if [ ! -d "$LOGS_DIR" ]; then
    echo "📁 Creating logs directory..."
    mkdir -p "$LOGS_DIR"
else
    echo "✅ Logs directory already exists"
fi

# Set proper permissions for logs directory
echo "🔒 Setting permissions for logs directory..."
chmod 755 "$LOGS_DIR"

# Create empty log files if they don't exist (prevents permission issues)
LOG_FILES=(
    "django.log"
    "requests.log"
    "storage.log"
    "errors.log"
    "video_upload.log"
    "storage_operations.log"
)

for log_file in "${LOG_FILES[@]}"; do
    log_path="$LOGS_DIR/$log_file"
    if [ ! -f "$log_path" ]; then
        echo "📝 Creating $log_file..."
        touch "$log_path"
        chmod 644 "$log_path"
    else
        echo "✅ $log_file already exists"
    fi
done

# Set ownership for web server (if running as root)
if [ "$EUID" -eq 0 ]; then
    echo "🔒 Setting ownership for web server..."
    
    # Try different common web server users
    if id "www-data" &>/dev/null; then
        chown -R www-data:www-data "$LOGS_DIR"
        echo "✅ Set ownership to www-data"
    elif id "nginx" &>/dev/null; then
        chown -R nginx:nginx "$LOGS_DIR"
        echo "✅ Set ownership to nginx"
    elif id "apache" &>/dev/null; then
        chown -R apache:apache "$LOGS_DIR"
        echo "✅ Set ownership to apache"
    else
        echo "⚠️  Could not determine web server user, keeping current ownership"
    fi
else
    echo "ℹ️  Not running as root, skipping ownership changes"
fi

# Test logging configuration
echo "🧪 Testing Django logging configuration..."
cd "$BACKEND_DIR"

if python manage.py check --deploy > /dev/null 2>&1; then
    echo "✅ Django configuration is valid"
else
    echo "❌ Django configuration has issues"
    echo "Running detailed check..."
    python manage.py check --deploy
    exit 1
fi

# Test logging system
echo "🧪 Testing logging system..."
if [ -f "$BACKEND_DIR/test_logging.py" ]; then
    if python test_logging.py > /dev/null 2>&1; then
        echo "✅ Logging system test passed"
    else
        echo "⚠️  Logging system test had issues (check manually)"
    fi
else
    echo "ℹ️  Logging test script not found, skipping test"
fi

# Display log file status
echo ""
echo "📊 Log files status:"
echo "==================="
for log_file in "${LOG_FILES[@]}"; do
    log_path="$LOGS_DIR/$log_file"
    if [ -f "$log_path" ]; then
        size=$(du -h "$log_path" | cut -f1)
        perms=$(ls -l "$log_path" | cut -d' ' -f1)
        owner=$(ls -l "$log_path" | cut -d' ' -f3-4)
        echo "✅ $log_file ($size, $perms, $owner)"
    else
        echo "❌ $log_file (missing)"
    fi
done

echo ""
echo "🎉 Logging infrastructure setup complete!"
echo ""
echo "📋 Next steps:"
echo "   1. Restart your Django application (gunicorn/uwsgi)"
echo "   2. Test video upload functionality"
echo "   3. Check logs are being written: tail -f logs/django.log"
echo "   4. Use analysis script: python scripts/analyze_logs.py --last-minutes 10"
echo ""
echo "📁 Log files location: $LOGS_DIR"
echo "🔍 Analysis script: $BACKEND_DIR/scripts/analyze_logs.py"
echo "🧪 Test script: $BACKEND_DIR/test_logging.py"