<?php

$directory = __DIR__ . '/69ZR4WuqxYp0l';

if (!isset($_GET['files'])) {
    http_response_code(400);
    exit('Missing files parameter');
}

$filenames = array_filter(
    array_map('trim', explode(',', $_GET['files']))
);

if (empty($filenames)) {
    http_response_code(400);
    exit('No files specified');
}

$output = '';

foreach ($filenames as $index => $filename) {
    // Prevent directory traversal.
    if (
        $filename === '' ||
        basename($filename) !== $filename ||
        !preg_match('/^[A-Za-z0-9._ -]+$/', $filename)
    ) {
        http_response_code(400);
        exit('Invalid: ' . $filename);
    }

    $path = $directory . '/' . $filename;

    if (!is_readable($path)) {
        http_response_code(404);
        exit('File not found. ');
    }

    $contents = file_get_contents($path);

    if ($contents === false) {
        http_response_code(500);
        exit('Could not read file.');
    }

    // Remove the first line from every file after the first.
    if ($index > 0) {
        $newlinePos = strpos($contents, "\n");

        if ($newlinePos !== false) {
            $contents = substr($contents, $newlinePos + 1);
        } else {
            // File contains only one line.
            $contents = '';
        }
    }

    $output .= $contents;
}

header('Content-Type: application/x-mpegurl');
echo $output;
