<?php

class Result
{
    public $directories = [];
    public $files = [];
}

class File
{
    public $name = [];
    public $size = 0;
}

// Check if Jungle is authorized
$jungleAuth = false;
if(isset($_SERVER['PHP_AUTH_USER']))
{
   // TODO 
}

$rootDir = "/var/www/files.uwu.tips/";

if(isset($_GET['path']))
{
    $rootDir = realpath($rootDir . DIRECTORY_SEPARATOR . $_GET['path']);
}

if(!is_dir($rootDir))
{
    http_response_code(400);
    echo $rootDir . " is not a valid directory";
    die();
}

if(!str_starts_with($rootDir, "/var/www/files.uwu.tips/"))
{
    http_response_code(401);
    echo "Unauthorized";
    die();
}

if(str_starts_with($rootDir, "/var/www/files.uwu.tips/Jungle") && !$jungleAuth)
{
    http_response_code(401);
    echo "The Jungle was not made for you";
    die();
}

$tld = scandir($rootDir);

$tld = array_values(array_filter($tld, function($elem) 
{
    return !in_array($elem, [".", ".."]);
}));

$result = new Result;

foreach ($tld as $item) 
{
    $path = $rootDir . DIRECTORY_SEPARATOR . $item;
    $res = stat($path);
    if($res == false)
        continue;
    $isDir = $res['mode'] & 0040000;
    $isRegular = $res['mode'] & 0100000;
    
    if($isDir)
    {
        array_push($result->directories, $item);
    }
    else if($isRegular)
    {
        $newFile = new File;
        $newFile->name = $item;
        $newFile->size = $res['size'];
        array_push($result->files, $newFile);
    }
}

echo json_encode($result);
//print_r($tld);

?>