<?php

class Result
{
    public $directories = [];
    public $files = [];
}

class File
{
    public $name = [];
    public $size = 0;
}

function readableBytes($inBytes)
{
    $suffexes = ["Bytes", "KB", "MB", "GB", "TB"];
    
    $inBytes = max($inBytes, 0);
    
    $base = floor(log($inBytes, 1024));
    
    $div = pow(1024, $base);
    
    return sprintf("%.1f %s", ($inBytes / $div), $suffexes[$base]);
}

// Check if Jungle is authorized
$jungleAuth = false;
if(isset($_SERVER['PHP_AUTH_USER']))
{
    // TODO 
    $uname = $_SERVER['PHP_AUTH_USER'];
    $rawpw = $_SERVER['PHP_AUTH_PW'];
    
    $descriptors = [
        ["pipe", "r"], // stdin
        ["file", "/dev/null", "w"], // stdout
        ["file", "/dev/null", "w"] // stderr
    ];
    
    $proc = proc_open('htpasswd -v Jungle/.htpasswd ' . $uname, $descriptors, $pipes);
    
    fwrite($pipes[0], $rawpw);
    fclose($pipes[0]);
    
    $retval = proc_close($proc);
    
    if($retval == 0)
    {
        $jungleAuth = true;
    }
}

$rootDir = "/var/www/files.uwu.tips/";

$path = "";
if(isset($_GET['path']))
{
    $path = $_GET['path'];
}

$rootDir = realpath($rootDir . DIRECTORY_SEPARATOR . $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)
{
    header('WWW-Authenticate: Basic realm="Jungle"');
    header('HTTP/1.0 401 Unauthorized');
    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) 
{
    $itemPath = $rootDir . DIRECTORY_SEPARATOR . $item;
    $res = stat($itemPath);
    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);
    }
}
?>

<html>

<head>
    <meta http-equiv="Cache-control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <script src="./index.js"></script>
    <style>
        body {
            background-color: rgb(46, 209, 73);
        }

        .box {
            width: 50%;
            float: left;
        }
        
        .icon {
            width: 25px;
            height: 25px;
        }
    </style>
</head>

<body>
    <audio id="backgroundAudio">
        <source src="web/sounds/background.mp3" type="audio/mpeg">
    </audio>

    <marquee width="100%" direction="right">
        Welcome to files.uwu.tips! Click a link! ;&#41
    </marquee>
    <br>
    <img src="web/logo.png" style="vertical-align: top;" />
    <a href="web/stick.gif">
        <img src="web/dogecoin.png" height="88px" style="float: right;" />
    </a>
    <img src="web/qr-code.png" height="88px" style="float: right;" />
    <br>
    
    <table>
        <?php if(realpath("/" . $path) != "/"): ?>
        <tr>
            <td>
                <img class="icon" src="./web/arrow-up.png" />
            </td>
            <td>
            <a href=<?php echo "?path=" . rawurlencode(realpath($path . "/..")) ?>>
            ..
            </a>
            </td>
        </tr>
        <?php endif; ?>
        <?php foreach($result->directories as $dir): ?>
        <tr>
            <td>
                <img class="icon" src="./web/folder.png" />
            </td>
            <td>
            <a href=<?php echo "?path=" . rawurlencode($path . "/" . $dir) ?>>
            <?=$dir?>
            </a>
            </td>
        </tr>
        <?php endforeach; ?>
        <?php foreach($result->files as $file): ?>
        <tr>
            <td>
                <img class="icon" src="./web/doc.png" />
            </td>
            <td>
            <a href=<?php echo rawurlencode($path . "/" . $file->name) ?>>
            <?=$file->name . " [" . readableBytes($file->size) . "]" ?>
            </a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    
    &copy 2023 Joe Mamma, Squidward, and Squilliam
    <button id="toggleSounds">Toggle Sounds</button>
</body>

</html>