<?php

$user = "mgmgmgmgyyyy2-boop";
$repo = "blue";
$path = "ts_files";

$url = "https://api.github.com/repos/$user/$repo/contents/$path";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => "PHP"
]);

$res = curl_exec($ch);
curl_close($ch);

$files = json_decode($res, true);

$segments = [];

foreach ($files as $file) {
    if (
        isset($file['name']) &&
        str_ends_with($file['name'], '.ts')
    ) {
        $segments[] = $file['download_url'];
    }
}

sort($segments, SORT_NATURAL);

$total = count($segments);

if ($total < 20) {
    die("Not enough TS files");
}

$wanted = array_slice($segments, $total - 20, 10);

header("Content-Type: application/vnd.apple.mpegurl");

echo "#EXTM3U\n";
echo "#EXT-X-VERSION:3\n";

foreach ($wanted as $ts) {
    echo "#EXTINF:10,\n";
    echo $ts . "\n";
}