<?php
# Copyright © 2014, 2016-2017 Luke Shumaker <lukeshu@sbcglobal.net>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the ./COPYING file for more details.

// Configuration
$repos = [
	'packages' => [ 'core', 'extra', 'staging', 'testing', 'gnome-unstable', 'kde-unstable' ],
	'community' => [ 'community', 'multilib' ],
	'parabola' => [ 'libre',
                    'libre-multilib',
	               'cross', 'java', 'kernels', 'nonprism', 'pcr' ],
	'testing' => ['gnome-unstable', 'kde-unstable']
];

// Automatic configuration
$asseturl = dirname($_SERVER["SCRIPT_NAME"]);
$assetdir = dirname($_SERVER["SCRIPT_FILENAME"]);
$root = $_SERVER["DOCUMENT_ROOT"];
$dirname = explode("?", $_SERVER["REQUEST_URI"], 2)[0];

////////////////////////////////////////////////////////////////////////////////

function normalizeN($filename) {
	$parts = preg_split("|/+|", $filename, -1, PREG_SPLIT_NO_EMPTY);
	$abs = $filename[0] === '/';
	return [ ($abs?'/':'').implode('/', $parts), count($parts) ];
}

function normalize($filename) {
	list ($new_filename, $n) = normalizeN($filename);
	return $new_filename;
}

function is_root($root, $dirname) {
	$path = $root.'/'.$dirname;
	return (normalize($path) === normalize($root));
}

function has_suffix($str, $suffix) {
	return substr($str, -strlen($suffix)) === $suffix;
}

function trim_suffix($str, $suffix) {
	return has_suffix($str, $suffix) ? substr($str, 0, -strlen($suffix)) : $str;
}

function s_is_type($mode, $mask) { return ($mode & 0170000/*<sys/stat.h>:S_IFMT*/) === $mask; } // <sys/stat.h>:__S_ISTYPE
function stat_is_dir( $stat) { return s_is_type($stat['mode'], 0040000/*<sys/stat.h>:S_IFDIR*/); }
function stat_is_file($stat) { return s_is_type($stat['mode'], 0100000/*<sys/stat.h>:S_IFREG*/); }
function stat_is_link($stat) { return s_is_type($stat['mode'], 0120000/*<sys/stat.h>:S_IFLNK*/); }

function classify($root, $dirname, $filename) {
	global $repos;

	list ($dirname, $parts) = normalizeN($dirname);
	$filepath = $root.'/'.$dirname.'/'.$filename;
	$stat = lstat($filepath);

	if ($filename === '.' ) { return [ [ 'dir'           ], $stat]; }
	if ($filename === '..') { return [ [ 'dir', 'parent' ], $stat]; }

	$classes = array();

	if (stat_is_link($stat)) {
		$classes[] = 'link';
		$lstat = $stat;
		$stat = stat($filepath);
	}

	if ($parts == 0) {
		// in the top-level
		if (stat_is_dir($stat) && is_dir($filepath.'/os')) {
			array_push($classes, 'repo');
			foreach (array_keys($repos) as $category) {
				if (in_array($filename, $repos[$category])) {
					array_push($classes, $category);
				}
				if (in_array(trim_suffix($filename, "-staging"), $repos[$category])) {
					array_push($classes, $category);
				}
				if (in_array(trim_suffix($filename, "-testing"), $repos[$category])) {
					array_push($classes, $category);
				}
			}
			if (has_suffix($filename, "staging")) { array_push($classes, 'staging'); }
			if (has_suffix($filename, "testing")) { array_push($classes, 'testing'); }
			if ($filename[0] === '~') { array_push($classes, 'parabola'); }
		}
	} elseif ($dirname == "/pool" || $dirname == "/sources") {
		array_push($classes, 'pool', $filename);
	}
	if ($filename[0] === '.' || substr($filename, -1) === '~') { $classes[] = 'hidden'; }
	if (stat_is_dir( $stat)) { $classes[] = 'dir';  }
	if (stat_is_file($stat)) { $classes[] = 'file'; }

	if (preg_match("/\.pkg\.tar(\..z)?$/" , $filename) == 1) { $classes[] = 'pkg'; }
	if (preg_match("/\.tar(\..z|\.bz2)?$/", $filename) == 1) { $classes[] = 'tar'; }
	$classes[] = pathinfo($filename, PATHINFO_EXTENSION);

	if (isset($lstat)) {
		$stat = $lstat;
	}
	return [ $classes, $stat ];
}

////////////////////////////////////////////////////////////////////////////////

if (!is_dir($root.'/'.$dirname)) {
	if (is_file($root.'/'.$dirname)) {
		header('Content-Type: text/plain'); // gross, but if Nginx is "properly" configured, this only happens when serving itself, which is text
		readfile($root.'/'.$dirname);
	} else {
		require $assetdir.'/404.php';
	}
	exit(0);
}

////////////////////////////////////////////////////////////////////////////////
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Parabola GNU/Linux-libre - Index of <?php echo htmlentities($dirname); ?></title>
    <link rel="stylesheet" type="text/css" href="<?php echo $asseturl."/style.css"; ?>" />
    <link rel="icon" type="image/x-icon" href="https://www.parabola.nu/static/favicon.72ab042ac877.ico" />
    <link rel="shortcut icon" type="image/x-icon" href="https://www.parabola.nu/static/favicon.72ab042ac877.ico" />
    <link rel="apple-touch-icon" href="https://www.parabola.nu/static/logos/apple-touch-icon-57x57.6484c8e17e2f.png" />
    <link rel="apple-touch-icon" sizes="72x72" href="https://www.parabola.nu/static/logos/apple-touch-icon-72x72.f60f1458fe1c.png" />
    <link rel="apple-touch-icon" sizes="114x114" href="https://www.parabola.nu/static/logos/apple-touch-icon-114x114.e7845a2e4bab.png" />
    <link rel="apple-touch-icon" sizes="144x144" href="https://www.parabola.nu/static/logos/apple-touch-icon-144x144.97a164b5f85c.png" />
    <link rel="search" type="application/opensearchdescription+xml" href="https://www.parabola.nu/opensearch/packages/" title="Parabola GNU/Linux-libre Packages" />
<!--
    <style>
    #inner-table-td { width: 32em ; height: 100% ; }
    #content { }
    #abox { width: 24em ; height: 100% ; position: absolute ; overflow: scroll ; }
    #archdev-iframe { position: absolute ; left: 27em ; width: 100% ; height: 100% }
    </style>
-->
</head>
<body>
    <div id="archnavbar" class="anb-repo">
        <div id="archnavbarlogo"><h1><a href="/" title="Return to the main page">Parabola</a></h1></div>
        <div id="archnavbarmenu">
            <ul id="archnavbarlist">
                <li id="anb-home"><a href="https://www.parabola.nu/" title="Parabola news, packages, projects and more">Home</a></li>
                <li id="anb-packages"><a href="https://www.parabola.nu/packages/" title="Parabola Package Database">Packages</a></li>
                <!-- Free Culture or multimedia with mediagoblin -->
                <!-- Social with GNU Social, Diaspora or another, it needs consensus -->
                <li id="anb-wiki"><a href="https://wiki.parabola.nu/" title="Community documentation">Wiki</a></li>
                <li id="anb-forum"><a href="https://labs.parabola.nu/projects/parabola-community-forum" title="Parabola Community Forum">Forum</a></li>
                <li id="anb-bugs"><a href="https://labs.parabola.nu/" title="Report and track bugs">Issues</a></li>
                <!-- security -->
                <!-- PUR -->
                <li id="anb-projects"><a href="https://projects.parabola.nu/" title="Our code">Projects</a></li>
                <li id="anb-download"><a href="https://www.parabola.nu/download" title="Get Parabola">Download</a></li>
            </ul>
        </div>
    </div><!-- #archnavbar -->
<!--
    <div id="archdev-navbar">archdev-navbar</div>
-->
    <div id="content" class="index-content">

        <div id="downloads-div">All Downloads</h2>
<!--
<table id="inner-table"><tr><td id="inner-table-td">
-->
                <div id="abox" class="box">
<!--
                            width="20%" height="100%">
-->
<!--
		<div class="box">
-->
			<h2>Index of <?php echo htmlentities($dirname); ?></h2>


			<tr><td>
			<!--
			<table id="index-table" width="300px" height="100%"><tbody><tr><td>
			-->
			<table><tbody>
<?php
					if ($dh = opendir($root.'/'.$dirname)) {
						$filenames = array();
						while (($filename = readdir($dh)) !== false) { $filenames[] = $filename; }
						closedir($dh);
						sort($filenames);
						foreach ($filenames as $filename) {
							if ($filename === '.') { continue; }
							if ($filename === '..' && is_root($root,$dirname)) { continue; }
							list($classes, $stat) = classify($root, $dirname, $filename);
							echo "\t\t\t\t<tr class=\"".implode(' ', $classes)."\">";

							echo "<td>";
							if (stat_is_dir($stat)) {
								// stick a trailing slash on the URL; save a round-trip, since nginx will add it
								// with a redirect
								echo "<a href=\"".htmlentities($filename)."/\">".htmlentities($filename)."</a>";
							} else {
								echo "<a href=\"./".htmlentities($filename)."\">".htmlentities($filename)."</a>";
							}
							if (stat_is_link($stat)) {
								$target = readlink($root.'/'.$dirname.'/'.$filename);
								echo " -&gt; <a href=\"".htmlentities($target)."\">".htmlentities($target)."</a>";
							}
							echo "</td>";

							if ($filename === '..') {
								echo '<td></td><td></td>';
							} else {
								echo "<td>".date("Y-m-d H:i", $stat['mtime'])."</td>";
								if (stat_is_dir($stat)) {
									echo "<td class=number>-</td>";
								} else {
									echo "<td class=number>".$stat['size']."</td>";
								}
							}
							echo "</tr>\n";
						}
					}
?>
			</tbody></table>
<!-- in box
			</td><td>td</td></tr></table>
-->
		</div> <!-- box -->
<!--
		</td><td id="outter-td"> outer
		</td></tr></ta
-->
<!--
		<div id="archdev-inout">archdev-inout</div>
-->
<!--
<iframe id="archdev-iframe" src="/download"></iframe>
-->
	</div> <!-- # content-div -->

<!--	<div id="archdev-out">archdev-out</div> -->

<!--
	<iframe id="archdev-iframe" src="https://labs.parabola.nu/downloads" />
-->
<!--
<iframe id="archdev-iframe" src="/download" />
-->

</body>
</html>
