#!/usr/bin/php
<?php

// Usage: "port file all | php ports_using_cd.php"
// Author: Ryan Schmidt <ryandesign@macports.org>
// License: public domain

$total_ports = 0;
$bad_ports = $bad_maintainers = array();
while (!feof(STDIN)) {
	$portfile = trim(fgets(STDIN));
	if (!file_exists($portfile)) continue;
	++$total_ports;
	
	$contents = file_get_contents($portfile);
	
	// Censor some parts of the portfile. Replace non-space characters with "#".
	// Don't just remove the affected bits because we want to maintain line numbers.
	$search = array();
	$search[] = '%^(\\s*#)(.*)$%me'; // comments
	$search[] = '%(\\W)((?:system|ui_(?:error|info|msg))\\s+".*?[^\\\\]")%se'; // system and ui_* calls
	$search[] = '%(\\W)(\\w+\\.cmd\\s+cd\\s.*?[^\\\\]\\n)%se'; // configure.cmd, build.cmd, etc.
	$replace = '\'\\1\' . preg_replace(\'%\\S%\', \'#\', \'\\2\')';
	$contents = preg_replace($search, $replace, $contents);
	
	// Examine each line for the offending command.
	$lines = preg_split("%\n%", $contents);
	foreach ($lines as $line_num => $line) {
		if (preg_match('%(^|\\s)cd\\s%', $line)) {
			if (!in_array($portfile, $bad_ports)) $bad_ports[] = $portfile;
			echo $portfile . ':' . $line_num . ' ' . $line . "\n";
		}
	}
}

if ($total_ports > 0) {
	if (empty($bad_ports)) {
		fwrite(STDERR, "None of these $total_ports ports are using the 'cd' command.\n");
	} else {
		fwrite(STDERR, "\nOf these $total_ports ports, " . count($bad_ports) . " are using the 'cd' command, maintained by:\n");
		foreach ($bad_ports as $bad_port) {
			fwrite(STDERR, '.');
			$maintainers = exec("port info --maintainer " . escapeshellarg(dirname($bad_port)));
			$maintainers = preg_replace('%^maintainer: %', '', $maintainers);
			$maintainers = preg_split('%, %', $maintainers);
			foreach ($maintainers as $maintainer) {
				if (!isset($bad_maintainers[$maintainer])) {
					$bad_maintainers[$maintainer] = 1;
				} else {
					++$bad_maintainers[$maintainer];
				}
			}
		}
		ksort($bad_maintainers);
		fwrite(STDERR, "\n");
		foreach ($bad_maintainers as $bad_maintainer => $num_bad_ports) {
			fwrite(STDERR, $bad_maintainer . ' (' . $num_bad_ports . ')' . "\n");
		}
	}
}

?>

