<?php
date_default_timezone_set('Europe/Copenhagen');
$config = require __DIR__ . "/config.php";
function x($s){ return htmlspecialchars((string)$s, ENT_XML1 | ENT_QUOTES, "UTF-8"); }
function nice_title($s){ return trim(ucwords(str_replace(['_','-'], ' ', $s))); }
function hidden_video_outputs($config){
    $hidden = [];
    foreach (glob($config['uploads_dir'].'/*', GLOB_ONLYDIR) ?: [] as $dir) {
        if (!is_file($dir . '/.mvlog-hidden')) continue;
        $state = is_file($dir . '/.movmaker-state.json') ? json_decode((string)file_get_contents($dir . '/.movmaker-state.json'), true) : [];
        if (is_array($state) && !empty($state['output'])) $hidden[basename((string)$state['output'])] = true;
    }
    return $hidden;
}
function video_metadata($path){
    $base = pathinfo($path, PATHINFO_FILENAME);
    $meta = ['title'=>nice_title($base),'date'=>date('Y-m-d',filemtime($path)),'location'=>'','description'=>''];
    if (preg_match('/^(\d{4})(\d{2})(\d{2})[_-](.+)$/', $base, $m)) { $meta['date']="$m[1]-$m[2]-$m[3]"; $meta['title']=nice_title($m[4]); }
    $ffprobe = trim((string)shell_exec('command -v ffprobe 2>/dev/null'));
    if ($ffprobe !== '') {
        $json = shell_exec(escapeshellarg($ffprobe).' -v quiet -print_format json -show_entries format_tags '.escapeshellarg($path).' 2>/dev/null');
        $data = json_decode((string)$json, true); $tags = $data['format']['tags'] ?? []; $lower=[];
        foreach($tags as $k=>$v) $lower[strtolower($k)]=$v;
        if(!empty($lower['title'])) $meta['title']=$lower['title'];
        if(!empty($lower['date'])) $meta['date']=$lower['date'];
        foreach(['location','place','com.apple.quicktime.location.name'] as $k) if(!empty($lower[$k])) { $meta['location']=$lower[$k]; break; }
        foreach(['description','synopsis'] as $k) if(!empty($lower[$k])) { $meta['description']=$lower[$k]; break; }
    }
    return $meta;
}
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'https';
$host = $_SERVER['HTTP_HOST'] ?? 'bubulescu.org';
$baseUrl = $scheme . '://' . $host . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$hiddenOutputs = hidden_video_outputs($config);
$videos = array_values(array_filter(glob($config['videos_dir'].'/*.{mp4,webm,mov,m4v}', GLOB_BRACE) ?: [], fn($v)=>empty($hiddenOutputs[basename($v)]) && !preg_match('/_preview\.(mp4|webm|mov|m4v)$/i', basename($v)) && !preg_match('/_preview\.(mp4|webm|mov|m4v)$/i', basename($v))));
usort($videos, fn($a,$b)=>filemtime($b)<=>filemtime($a));
$videos = array_slice($videos,0,20);
header('Content-Type: application/rss+xml; charset=UTF-8');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<rss version="2.0">
<channel>
<title>MVLog - Bubulescu.Org</title>
<link><?=x($baseUrl . '/')?></link>
<description>Latest videos from MVLog Bubulescu.Org</description>
<language>en</language>
<lastBuildDate><?=date(DATE_RSS)?></lastBuildDate>
<?php foreach($videos as $v): $name=basename($v); $m=video_metadata($v); $url=$baseUrl.'/out-dir/'.rawurlencode($name); $desc=trim(($m['location'] ? $m['location'].'. ' : '').$m['description']); ?>
<item>
<title><?=x($m['title'])?></title>
<link><?=x($url)?></link>
<guid isPermaLink="true"><?=x($url)?></guid>
<pubDate><?=date(DATE_RSS, filemtime($v))?></pubDate>
<description><?=x($desc)?></description>
<enclosure url="<?=x($url)?>" length="<?=filesize($v)?>" type="video/mp4" />
</item>
<?php endforeach; ?>
</channel>
</rss>
