#!/bin/bash

# Boot Performance Analysis Script for Simple-CLI
# This script analyzes and optimizes boot performance

set -e

echo "=== Simple-CLI Boot Performance Analysis ==="
echo ""

# Function to measure boot time
measure_boot_time() {
    echo "📊 Measuring boot performance..."
    
    if command -v systemd-analyze >/dev/null 2>&1; then
        echo "⏱️  Total boot time:"
        systemd-analyze time
        
        echo ""
        echo "🐌 Slowest services:"
        systemd-analyze blame | head -10
        
        echo ""
        echo "🔗 Critical boot chain:"
        systemd-analyze critical-chain
        
        echo ""
        echo "📈 Boot timeline:"
        systemd-analyze plot > /tmp/boot-timeline.svg 2>/dev/null && echo "Timeline saved to /tmp/boot-timeline.svg" || echo "Timeline generation failed"
    else
        echo "❌ systemd-analyze not available"
    fi
}

# Function to check boot configuration
check_boot_config() {
    echo ""
    echo "🔍 Checking boot configuration..."
    
    # Check GRUB configuration
    if [ -f /etc/default/grub ]; then
        echo "✅ GRUB config found"
        echo "   Timeout: $(grep GRUB_TIMEOUT /etc/default/grub || echo 'Not set')"
        echo "   Kernel params: $(grep GRUB_CMDLINE_LINUX /etc/default/grub || echo 'Not set')"
    else
        echo "❌ GRUB config not found"
    fi
    
    # Check systemd configuration
    if [ -f /etc/systemd/system.conf.d/99-boot-performance.conf ]; then
        echo "✅ Boot performance config found"
        cat /etc/systemd/system.conf.d/99-boot-performance.conf
    else
        echo "❌ Boot performance config not found"
    fi
    
    # Check kernel parameters
    if [ -f /etc/sysctl.d/99-boot-performance.conf ]; then
        echo "✅ Kernel performance config found"
        cat /etc/sysctl.d/99-boot-performance.conf
    else
        echo "❌ Kernel performance config not found"
    fi
}

# Function to enable verbose boot logging
enable_verbose_logging() {
    echo ""
    echo "🔧 Enabling verbose boot logging..."
    
    # Enable verbose GRUB logging
    if [ -f /etc/default/grub ]; then
        sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="[^"]*"/GRUB_CMDLINE_LINUX_DEFAULT="console=ttyS0 root=\/dev\/sda1 rw quiet splash fastboot loglevel=7"/' /etc/default/grub
        echo "✅ Verbose GRUB logging enabled"
    fi
    
    # Enable verbose systemd logging
    mkdir -p /etc/systemd/system.conf.d
    cat > /etc/systemd/system.conf.d/99-verbose-boot.conf << EOF
[Manager]
LogLevel=debug
LogTarget=console
EOF
    echo "✅ Verbose systemd logging enabled"
    
    # Enable verbose kernel logging
    mkdir -p /etc/sysctl.d
    echo "kernel.printk = 7 4 1 7" > /etc/sysctl.d/99-verbose-kernel.conf
    echo "✅ Verbose kernel logging enabled"
}

# Function to optimize boot performance
optimize_boot() {
    echo ""
    echo "⚡ Optimizing boot performance..."
    
    # Disable unnecessary services
    systemctl disable systemd-networkd-wait-online.service 2>/dev/null || true
    systemctl disable systemd-resolved.service 2>/dev/null || true
    
    # Enable parallel boot
    mkdir -p /etc/systemd/system.conf.d
    cat > /etc/systemd/system.conf.d/99-parallel-boot.conf << EOF
[Manager]
DefaultTimeoutStartSec=15s
DefaultTimeoutStopSec=15s
DefaultRestartSec=100ms
EOF
    echo "✅ Parallel boot enabled"
    
    # Optimize kernel parameters
    cat > /etc/sysctl.d/99-boot-optimization.conf << EOF
# Boot performance optimizations
kernel.printk = 3 4 1 3
vm.swappiness = 1
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
# Reduce boot time
kernel.randomize_va_space = 0
EOF
    echo "✅ Kernel optimizations applied"
}

# Main execution
case "${1:-analyze}" in
    "analyze")
        measure_boot_time
        check_boot_config
        ;;
    "verbose")
        enable_verbose_logging
        ;;
    "optimize")
        optimize_boot
        ;;
    "all")
        measure_boot_time
        check_boot_config
        enable_verbose_logging
        optimize_boot
        ;;
    *)
        echo "Usage: $0 [analyze|verbose|optimize|all]"
        echo "  analyze  - Measure and analyze boot performance"
        echo "  verbose  - Enable verbose boot logging"
        echo "  optimize - Apply boot performance optimizations"
        echo "  all      - Run all optimizations"
        exit 1
        ;;
esac

echo ""
echo "✅ Boot performance analysis complete!"
