#!/usr/bin/php
<?php

define('PORT', '/opt/local/bin/port');
if (!is_executable(PORT)) {
	fwrite(STDERR, sprintf('Can\'t execute %s', PORT) . "\n");
	exit(1);
}
define('PORTINDEX', dirname(dirname(exec(PORT . ' dir MacPorts'))) . '/PortIndex');

$exclude_maintainers = array(
	'openmaintainer@macports.org',
	'nomaintainer@macports.org',
);

$fh = fopen(PORTINDEX, 'rb');
$i = 0;
$maintainers = array();
while (!feof($fh)) {
	++$i;
	$line = fgets($fh);
	if ($i % 2) continue;
	while (!empty($line)) {
		$key = take_token($line);
		$value = take_token($line);
		if ('maintainers' == $key) {
			if (preg_match('%^\{(.*)\}$%', $value, $matches)) {
				$new_maintainers = explode(' ', $matches[1]);
			} else {
				$new_maintainers = array($value);
			}
			foreach ($new_maintainers as $new_maintainer) {
				$maintainers[fix_maintainer($new_maintainer)] = true;
			}
		}
	}
}
fclose($fh);

foreach ($exclude_maintainers as $exclude_maintainer) {
	unset($maintainers[$exclude_maintainer]);
}

$maintainers = array_keys($maintainers);
sort($maintainers);
echo implode("\n", $maintainers) . "\n";

exit;

function take_token(&$line) {
	if (preg_match('%^(?:\{.*?\}|\S+)\s%', $line, $matches)) {
		$line = substr($line, strlen($matches[0]));
		$token = $matches[0];
		while (substr_count($token, '{') > substr_count($token, '}')) {
			if (preg_match('%^.*?\}\s%', $line, $matches)) {
				$line = substr($line, strlen($matches[0]));
				$token .= $matches[0];
			} else {
				fwrite(STDERR, 'Couldn\'t finish reading a token!' . "\n");
				exit(1);
			}
		}
		return rtrim($token);
	} else {
		fwrite(STDERR, 'Couldn\'t find a token!' . "\n");
		exit(1);
	}
}

function fix_maintainer($maintainer) {
	if (preg_match('%^([^:]+):([^:]+)$%', $maintainer, $matches)) {
		return $matches[2] . '@' . $matches[1];
	}
	if (false === strpos($maintainer, '@')) {
		return $maintainer . '@macports.org';
	}
	return $maintainer;
}

?>

