<?php

/**
 * UltyScan Web Interface - Scan Status & Log Streaming
 * Returns current scan status and log content as JSON
 */

header('Content-Type: application/json');

$logDir = '/var/log/ultyscan';

// Check if any sniper scan process is actually running
$output = shell_exec('ps aux 2>/dev/null | grep -E "sniper[[:space:]]+-[tmfwp]|sudo.*sniper" | grep -v "grep"');
$running = false;
$processes = [];

if (!empty($output)) {
    $lines = explode("\n", trim($output));
    foreach ($lines as $line) {
        $line = trim($line);
        if (!empty($line) && strpos($line, 'status.php') === false && strpos($line, 'php') === false) {
            $processes[] = $line;
        }
    }
    $running = count($processes) > 0;
}

// Get recent log files
$logs = [];
$latestLogContent = '';
$latestLogFile = '';

if (is_dir($logDir)) {
    $files = glob($logDir . '/scan_*.log');
    if ($files && is_array($files)) {
        usort($files, function ($a, $b) {
            return filemtime($b) - filemtime($a);
        });
        $logs = array_slice($files, 0, 5);

        // Get content of the latest log file
        if (count($logs) > 0) {
            $latestLogFile = $logs[0];
            // Read last 100 lines of the log file
            $content = file_get_contents($latestLogFile);
            if ($content !== false) {
                $allLines = explode("\n", $content);
                $lastLines = array_slice($allLines, -100);
                $latestLogContent = implode("\n", $lastLines);
            }
        }
    }
}

// Also check for currently running workspace output
$workspaceOutput = '';
if ($running && !empty($processes)) {
    // Try to find the workspace from the process
    foreach ($processes as $proc) {
        if (preg_match('/-w\s+[\'"]?([^\s\'"]+)/', $proc, $matches)) {
            $workspace = $matches[1];
            $workspaceLogDir = "/usr/share/sniper/loot/workspace/$workspace/output";
            if (is_dir($workspaceLogDir)) {
                $workspaceFiles = glob($workspaceLogDir . '/sniper-*.txt');
                if ($workspaceFiles && count($workspaceFiles) > 0) {
                    usort($workspaceFiles, function ($a, $b) {
                        return filemtime($b) - filemtime($a);
                    });
                    $latestFile = $workspaceFiles[0];
                    $content = file_get_contents($latestFile);
                    if ($content !== false) {
                        $allLines = explode("\n", $content);
                        $lastLines = array_slice($allLines, -50);
                        $workspaceOutput = implode("\n", $lastLines);
                    }
                }
            }
            break;
        }
    }
}

echo json_encode([
    'running' => $running,
    'processCount' => count($processes),
    'processes' => $processes,
    'recentLogs' => $logs,
    'latestLogFile' => basename($latestLogFile),
    'logContent' => $latestLogContent,
    'workspaceOutput' => $workspaceOutput,
    'timestamp' => date('Y-m-d H:i:s')
]);
