<?php

/**
 * UltyScan Web Interface - Git Version Info
 * Returns current git commit ID and age
 */

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

$gitDir = '/usr/share/sniper';

// Get commit hash
$commitHash = trim(shell_exec("cd $gitDir && git rev-parse --short HEAD 2>/dev/null"));
$fullHash = trim(shell_exec("cd $gitDir && git rev-parse HEAD 2>/dev/null"));

// Get commit date
$commitDate = trim(shell_exec("cd $gitDir && git log -1 --format=%ci 2>/dev/null"));
$commitTimestamp = strtotime($commitDate);

// Calculate age
$age = '';
if ($commitTimestamp) {
    $diff = time() - $commitTimestamp;

    if ($diff < 60) {
        $age = $diff . ' seconds ago';
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        $age = $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        $age = $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        $age = $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 2592000) {
        $weeks = floor($diff / 604800);
        $age = $weeks . ' week' . ($weeks > 1 ? 's' : '') . ' ago';
    } else {
        $months = floor($diff / 2592000);
        $age = $months . ' month' . ($months > 1 ? 's' : '') . ' ago';
    }
}

// Get branch
$branch = trim(shell_exec("cd $gitDir && git rev-parse --abbrev-ref HEAD 2>/dev/null"));

echo json_encode([
    'commit' => $commitHash,
    'fullCommit' => $fullHash,
    'branch' => $branch,
    'date' => $commitDate,
    'age' => $age,
    'timestamp' => $commitTimestamp
]);
