#!/usr/bin/env php
<?php
/*
 * Authored by Hayden.
 * This program is released into the public domain under CC0 1.0.
 */

if (empty($argv[1]) || !is_file($argv[1])) {
	exit("Invalid dinst file.\n");
}
$kdlpath = $argv[1];
$mdpath = __DIR__ . '/_index.md';

$kdl = file_get_contents($kdlpath);

$md = preg_replace_callback('@<pkglist group="(.+?)">.*?</pkglist>@s', function ($groups) use ($kdl) {
	$group = $groups[1];
	$count = preg_match(
		"~^group {$group} {.+?^}~ms",
		$kdl, $group_match
	);
	if (!$count) {
		exit("Error: group \"$group\" not found\n");
	}

	$buffer = "<pkglist group=\"$group\">\n\n";

	$count = preg_match_all(
		'~^\t// ([^\n]*)\n\tgroup \S+ {\n\t{2}(.+?)\n\t{,2}\S~ms',
		$group_match[0], $pkg_matches, PREG_SET_ORDER
	);
	if (!$count) {
		echo "Warning: no matched package in group \"$group\"\n";
		return "$buffer\n</pkglist>";
	}

	$buffer .= "| Package name | Description |\n| - | - |\n";

	foreach ($pkg_matches as $pkg_match) {
		$desc = $pkg_match[1];
		$dec = $pkg_match[2];

		preg_match(
			'~(\S+) (\x5c\n\t+)?"?([^"\s]+)"?+( // ([^\n]+))?~ms',
			$dec, $dec_parts
		);
		$backend = $dec_parts[1];
		$pkg = $dec_parts[3];
		$comment = $dec_parts[5] ?? null;

		$sup = match ($backend) {
			'composer-pkg' => 'Composer',
			'flatpak-pkg' => 'Flatpak',
			default => null
		};
		if ($backend == 'arch-pkg' && $comment == 'aur') {
			$sup = 'AUR';
		}
		if ($sup) $pkg .= "<sup>$sup</sup>";

		$buffer .= "| $pkg | $desc |\n";
	}

	return "$buffer\n</pkglist>";
}, file_get_contents($mdpath));

file_put_contents($mdpath, $md);
