#!/bin/bash
# Desk-Moloni v3.0 Performance Analysis and Report Generator
# Author: Descomplicar.pt
# Version: 3.0.0
# License: Commercial
set -e
# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DIR="$(dirname "$SCRIPT_DIR")"
REPORT_FILE="/tmp/desk-moloni-performance-report-$(date +%Y%m%d-%H%M%S).html"
JSON_REPORT="/tmp/desk-moloni-performance-data-$(date +%Y%m%d-%H%M%S).json"
PERFEX_ROOT=""
# Performance thresholds
SYNC_TIME_THRESHOLD=30 # seconds
SUCCESS_RATE_THRESHOLD=99.5 # percentage
API_RESPONSE_THRESHOLD=5 # seconds
QUEUE_RATE_THRESHOLD=1000 # tasks per hour
MEMORY_THRESHOLD=80 # percentage
CPU_THRESHOLD=80 # percentage
# Functions
log() {
echo -e "${GREEN}[PERF]${NC} $1"
}
warning() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1"
}
info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
# Find Perfex root directory
find_perfex_root() {
local current_dir="$MODULE_DIR"
while [[ "$current_dir" != "/" ]]; do
if [[ -f "$current_dir/application/config/app.php" ]]; then
PERFEX_ROOT="$current_dir"
return 0
fi
current_dir="$(dirname "$current_dir")"
done
return 1
}
# Performance banner
echo "========================================================================"
echo " DESK-MOLONI v3.0 PERFORMANCE REPORT"
echo "========================================================================"
echo "Report File: $REPORT_FILE"
echo "JSON Data: $JSON_REPORT"
echo "Analysis Date: $(date)"
echo ""
log "Starting comprehensive performance analysis..."
# Find Perfex installation
if ! find_perfex_root; then
error "Could not find Perfex CRM installation directory"
exit 1
fi
log "Perfex CRM root found: $PERFEX_ROOT"
# Initialize HTML report
cat > "$REPORT_FILE" << 'EOF'
EOF
# Initialize JSON report
cat > "$JSON_REPORT" << EOF
{
"report_meta": {
"version": "3.0.0",
"generated_at": "$(date -Iseconds)",
"module_path": "$MODULE_DIR",
"perfex_root": "$PERFEX_ROOT"
},
"metrics": {},
"recommendations": [],
"status": "unknown"
}
EOF
# 1. System Information
echo ""
log "=== COLLECTING SYSTEM INFORMATION ==="
SYSTEM_INFO=$(cat << EOF
{
"php_version": "$(php -r 'echo PHP_VERSION;')",
"memory_limit": "$(php -r 'echo ini_get("memory_limit");')",
"max_execution_time": "$(php -r 'echo ini_get("max_execution_time");')",
"server_software": "${SERVER_SOFTWARE:-Unknown}",
"operating_system": "$(uname -s -r)",
"cpu_cores": "$(nproc 2>/dev/null || echo 'Unknown')",
"total_memory": "$(free -h | awk '/^Mem:/ {print $2}' 2>/dev/null || echo 'Unknown')"
}
EOF
)
info "System Information collected"
# 2. Database Performance Analysis
echo ""
log "=== ANALYZING DATABASE PERFORMANCE ==="
DB_METRICS=""
if command -v mysql > /dev/null 2>&1; then
# Try to connect to database and get metrics
DB_METRICS=$(cat << 'EOF'
{
"connection_test": "attempting",
"table_sizes": {},
"query_performance": {},
"index_usage": {}
}
EOF
)
# Check if we can determine database connection details
if [[ -f "$PERFEX_ROOT/application/config/database.php" ]]; then
info "Database configuration found"
# Get table sizes (basic estimation)
TABLE_COUNT=$(find "$MODULE_DIR/database" -name "*.sql" | wc -l)
DB_METRICS=$(echo "$DB_METRICS" | jq ".table_count = $TABLE_COUNT")
else
warning "Database configuration not accessible"
fi
else
warning "MySQL client not available for database analysis"
DB_METRICS='{"status": "unavailable", "reason": "mysql client not found"}'
fi
info "Database metrics collected"
# 3. File System Performance
echo ""
log "=== ANALYZING FILE SYSTEM PERFORMANCE ==="
# Calculate directory sizes
MODULE_SIZE=$(du -sb "$MODULE_DIR" 2>/dev/null | cut -f1 || echo "0")
UPLOADS_SIZE=0
if [[ -d "$PERFEX_ROOT/uploads/desk_moloni" ]]; then
UPLOADS_SIZE=$(du -sb "$PERFEX_ROOT/uploads/desk_moloni" 2>/dev/null | cut -f1 || echo "0")
fi
# Count files
TOTAL_FILES=$(find "$MODULE_DIR" -type f | wc -l)
PHP_FILES=$(find "$MODULE_DIR" -name "*.php" | wc -l)
JS_FILES=$(find "$MODULE_DIR" -name "*.js" | wc -l)
CSS_FILES=$(find "$MODULE_DIR" -name "*.css" | wc -l)
FILESYSTEM_METRICS=$(cat << EOF
{
"module_size_bytes": $MODULE_SIZE,
"uploads_size_bytes": $UPLOADS_SIZE,
"total_files": $TOTAL_FILES,
"php_files": $PHP_FILES,
"js_files": $JS_FILES,
"css_files": $CSS_FILES,
"module_size_mb": $(echo "scale=2; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0")
}
EOF
)
info "File system metrics collected"
# 4. Code Quality Metrics
echo ""
log "=== ANALYZING CODE QUALITY ==="
# Lines of code analysis
TOTAL_LOC=0
PHP_LOC=0
JS_LOC=0
if [[ $PHP_FILES -gt 0 ]]; then
PHP_LOC=$(find "$MODULE_DIR" -name "*.php" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi
if [[ $JS_FILES -gt 0 ]]; then
JS_LOC=$(find "$MODULE_DIR" -name "*.js" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi
TOTAL_LOC=$((PHP_LOC + JS_LOC))
# Test coverage estimation
TEST_FILES=$(find "$MODULE_DIR" -name "*Test.php" | wc -l)
TEST_LOC=0
if [[ $TEST_FILES -gt 0 ]]; then
TEST_LOC=$(find "$MODULE_DIR" -name "*Test.php" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi
CODE_METRICS=$(cat << EOF
{
"total_lines_of_code": $TOTAL_LOC,
"php_lines_of_code": $PHP_LOC,
"js_lines_of_code": $JS_LOC,
"test_files": $TEST_FILES,
"test_lines_of_code": $TEST_LOC,
"test_coverage_estimate": $(echo "scale=2; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")
}
EOF
)
info "Code quality metrics collected"
# 5. Performance Simulation
echo ""
log "=== RUNNING PERFORMANCE SIMULATION ==="
# Simulate basic performance tests
START_TIME=$(date +%s.%N)
# Test file loading performance
if [[ -f "$MODULE_DIR/desk_moloni.php" ]]; then
php -l "$MODULE_DIR/desk_moloni.php" > /dev/null 2>&1
fi
# Test autoloader performance
if [[ -f "$MODULE_DIR/vendor/autoload.php" ]]; then
php -r "require_once '$MODULE_DIR/vendor/autoload.php';" > /dev/null 2>&1
fi
END_TIME=$(date +%s.%N)
LOAD_TIME=$(echo "$END_TIME - $START_TIME" | bc -l 2>/dev/null || echo "0")
# Memory usage estimation
MEMORY_USAGE=$(php -r "
\$start = memory_get_usage();
if (file_exists('$MODULE_DIR/vendor/autoload.php')) {
require_once '$MODULE_DIR/vendor/autoload.php';
}
echo memory_get_usage() - \$start;
" 2>/dev/null || echo "0")
PERFORMANCE_METRICS=$(cat << EOF
{
"module_load_time": "$LOAD_TIME",
"estimated_memory_usage": $MEMORY_USAGE,
"memory_usage_mb": $(echo "scale=2; $MEMORY_USAGE/1024/1024" | bc -l 2>/dev/null || echo "0")
}
EOF
)
info "Performance simulation completed"
# 6. Security Performance
echo ""
log "=== ANALYZING SECURITY PERFORMANCE ==="
# Check for security-related files
SECURITY_FILES=0
[[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && ((SECURITY_FILES++))
[[ -f "$MODULE_DIR/config/security.php" ]] && ((SECURITY_FILES++))
# Check for security patterns in code
ENCRYPTION_USAGE=$(grep -r "encrypt\|decrypt" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
OAUTH_USAGE=$(grep -r "oauth\|OAuth" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
SECURITY_METRICS=$(cat << EOF
{
"security_files": $SECURITY_FILES,
"encryption_usage_count": $ENCRYPTION_USAGE,
"oauth_implementation_count": $OAUTH_USAGE,
"security_score": $(echo "scale=2; ($SECURITY_FILES + $ENCRYPTION_USAGE + $OAUTH_USAGE) * 10" | bc -l 2>/dev/null || echo "0")
}
EOF
)
info "Security performance metrics collected"
# 7. Generate Performance Score
echo ""
log "=== CALCULATING PERFORMANCE SCORE ==="
# Calculate overall performance score
PERFORMANCE_SCORE=0
# File organization score (0-25 points)
if [[ $TOTAL_FILES -lt 100 && $MODULE_SIZE -lt 10000000 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $TOTAL_FILES -lt 200 && $MODULE_SIZE -lt 50000000 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 20))
else
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 10))
fi
# Code quality score (0-25 points)
if [[ $TEST_FILES -gt 10 && $PHP_FILES -gt 0 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $TEST_FILES -gt 5 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 5))
fi
# Security implementation score (0-25 points)
if [[ $SECURITY_FILES -gt 1 && $ENCRYPTION_USAGE -gt 5 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $SECURITY_FILES -gt 0 || $ENCRYPTION_USAGE -gt 0 ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 5))
fi
# Architecture score (0-25 points)
if [[ -f "$MODULE_DIR/composer.json" && -d "$MODULE_DIR/vendor" ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ -f "$MODULE_DIR/composer.json" ]]; then
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 10))
fi
# Determine performance grade
if [[ $PERFORMANCE_SCORE -ge 90 ]]; then
PERFORMANCE_GRADE="A+"
GRADE_COLOR="status-excellent"
elif [[ $PERFORMANCE_SCORE -ge 80 ]]; then
PERFORMANCE_GRADE="A"
GRADE_COLOR="status-excellent"
elif [[ $PERFORMANCE_SCORE -ge 70 ]]; then
PERFORMANCE_GRADE="B"
GRADE_COLOR="status-good"
elif [[ $PERFORMANCE_SCORE -ge 60 ]]; then
PERFORMANCE_GRADE="C"
GRADE_COLOR="status-warning"
else
PERFORMANCE_GRADE="D"
GRADE_COLOR="status-critical"
fi
info "Performance score calculated: $PERFORMANCE_SCORE/100 ($PERFORMANCE_GRADE)"
# 8. Compile final JSON report
echo ""
log "=== COMPILING FINAL REPORT ==="
FINAL_JSON=$(cat << EOF
{
"report_meta": {
"version": "3.0.0",
"generated_at": "$(date -Iseconds)",
"module_path": "$MODULE_DIR",
"perfex_root": "$PERFEX_ROOT",
"performance_score": $PERFORMANCE_SCORE,
"performance_grade": "$PERFORMANCE_GRADE"
},
"system_info": $SYSTEM_INFO,
"database_metrics": $DB_METRICS,
"filesystem_metrics": $FILESYSTEM_METRICS,
"code_metrics": $CODE_METRICS,
"performance_metrics": $PERFORMANCE_METRICS,
"security_metrics": $SECURITY_METRICS,
"recommendations": [
{
"category": "optimization",
"priority": "medium",
"description": "Consider implementing Redis caching for improved performance"
},
{
"category": "monitoring",
"priority": "high",
"description": "Set up performance monitoring for production environment"
},
{
"category": "testing",
"priority": "medium",
"description": "Increase test coverage for better code quality assurance"
}
]
}
EOF
)
echo "$FINAL_JSON" > "$JSON_REPORT"
# 9. Generate HTML report
log "=== GENERATING HTML REPORT ==="
# Update HTML report with actual data
sed -i "s/__REPORT_DATE__/$(date)/" "$REPORT_FILE"
cat >> "$REPORT_FILE" << EOF
๐ Performance Overview
$PERFORMANCE_GRADE
Performance Grade
$PERFORMANCE_SCORE/100
Overall Score
$(echo "scale=1; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0") MB
Module Size
๐พ System Information
| Metric | Value | Status |
| PHP Version | $(php -r 'echo PHP_VERSION;') | โ |
| Memory Limit | $(php -r 'echo ini_get("memory_limit");') | Good |
| Max Execution Time | $(php -r 'echo ini_get("max_execution_time");')s | Good |
| Operating System | $(uname -s -r) | โ |
๐ File System Analysis
$(echo "scale=0; $PHP_LOC" | bc -l 2>/dev/null || echo "0")
Lines of PHP Code
$(echo "scale=1; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")%
Test Coverage Est.
๐ Security Performance
| Security Feature | Implementation | Status |
| Encryption Library | $([[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && echo "Implemented" || echo "Not Found") | $([[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && echo "โ" || echo "โ ") |
| OAuth Implementation | $OAUTH_USAGE references found | Good |
| Input Validation | $(grep -r "filter_var\|htmlspecialchars" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l) patterns found | Good |
๐ Performance Recommendations
๐ก Immediate Improvements
- Enable OpCache: Configure PHP OpCache for better performance
- Database Optimization: Add proper indexes for query optimization
- Caching Strategy: Implement Redis caching for API responses
๐ Long-term Optimizations
- Load Testing: Perform comprehensive load testing
- Monitoring: Set up performance monitoring and alerting
- Code Optimization: Profile and optimize critical code paths
๐ง Development Best Practices
- Test Coverage: Increase unit test coverage to >80%
- Code Quality: Implement static analysis tools
- Documentation: Maintain comprehensive API documentation
๐ Performance Checklist
| Performance Factor | Current Status | Target | Action Required |
| Module Load Time | ${LOAD_TIME}s | <0.5s | $([[ $(echo "$LOAD_TIME < 0.5" | bc -l 2>/dev/null) == "1" ]] && echo "โ Met" || echo "โ Optimize") |
| Memory Usage | $(echo "scale=1; $MEMORY_USAGE/1024/1024" | bc -l 2>/dev/null || echo "0") MB | <64 MB | $([[ $(echo "$MEMORY_USAGE < 67108864" | bc -l 2>/dev/null) == "1" ]] && echo "โ Met" || echo "โ Optimize") |
| File Count | $TOTAL_FILES files | <200 files | $([[ $TOTAL_FILES -lt 200 ]] && echo "โ Met" || echo "โ Reduce") |
| Test Coverage | $(echo "scale=1; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")% | >80% | $([[ $(echo "$TEST_LOC*100/$PHP_LOC > 80" | bc -l 2>/dev/null) == "1" ]] && echo "โ Met" || echo "โ Increase") |
๐ Benchmark Results
Performance Metrics Summary
| Metric Category | Score | Weight | Contribution |
| File Organization | $([[ $TOTAL_FILES -lt 100 ]] && echo "25/25" || echo "20/25") | 25% | $([[ $TOTAL_FILES -lt 100 ]] && echo "Excellent" || echo "Good") |
| Code Quality | $([[ $TEST_FILES -gt 10 ]] && echo "25/25" || echo "15/25") | 25% | $([[ $TEST_FILES -gt 10 ]] && echo "Excellent" || echo "Good") |
| Security Implementation | $([[ $SECURITY_FILES -gt 1 ]] && echo "25/25" || echo "15/25") | 25% | $([[ $SECURITY_FILES -gt 1 ]] && echo "Excellent" || echo "Good") |
| Architecture | $([[ -f "$MODULE_DIR/composer.json" ]] && echo "25/25" || echo "10/25") | 25% | $([[ -f "$MODULE_DIR/composer.json" ]] && echo "Excellent" || echo "Fair") |
๐ฏ Next Steps
- Review Performance Score: Current score is $PERFORMANCE_SCORE/100 ($PERFORMANCE_GRADE)
- Implement Recommendations: Focus on high-priority optimizations
- Setup Monitoring: Implement performance monitoring in production
- Schedule Regular Audits: Run performance analysis monthly
- Load Testing: Perform comprehensive load testing before production
Generated by Desk-Moloni v3.0 Performance Analyzer
ยฉ 2025 Descomplicarยฎ. All rights reserved.
EOF
# 10. Display summary
echo ""
echo "========================================================================"
echo " PERFORMANCE ANALYSIS COMPLETE"
echo "========================================================================"
echo ""
printf "Performance Grade: %s\n" "$PERFORMANCE_GRADE"
printf "Overall Score: %d/100\n" "$PERFORMANCE_SCORE"
printf "Module Size: %.1f MB\n" "$(echo "scale=1; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0")"
printf "Total Files: %d\n" "$TOTAL_FILES"
printf "Lines of Code: %d\n" "$TOTAL_LOC"
printf "Test Files: %d\n" "$TEST_FILES"
echo ""
echo "Reports Generated:"
echo " ๐ HTML Report: $REPORT_FILE"
echo " ๐ JSON Data: $JSON_REPORT"
echo ""
# Performance recommendations
echo "๐ KEY RECOMMENDATIONS:"
if [[ $PERFORMANCE_SCORE -lt 70 ]]; then
echo " โ ๏ธ Performance needs significant improvement"
echo " ๐ง Focus on code optimization and testing"
elif [[ $PERFORMANCE_SCORE -lt 85 ]]; then
echo " โ
Good performance with room for improvement"
echo " ๐ Implement caching and monitoring"
else
echo " ๐ Excellent performance! Maintain current standards"
echo " ๐ Focus on monitoring and continuous optimization"
fi
echo ""
echo "========================================================================"
# Open report in browser if available
if command -v xdg-open > /dev/null 2>&1; then
log "Opening performance report in browser..."
xdg-open "$REPORT_FILE" 2>/dev/null &
elif command -v open > /dev/null 2>&1; then
log "Opening performance report in browser..."
open "$REPORT_FILE" 2>/dev/null &
fi
# Exit with appropriate code
if [[ $PERFORMANCE_SCORE -lt 60 ]]; then
exit 1
else
exit 0
fi