#!/usr/bin/php
<?php
if(!isset($_SERVER['argv'][1]) || in_array($_SERVER['argv'][1], array('--help', '-h', '-?'))) {
	help();
	exit;
}
$dir = $_SERVER['argv'][1];

$ite = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($ite) as $filename => $cur) {
	updateFile($filename);
}


function updateFile($filename) {
	$useblock = $block = array();
	$updated = false;
	foreach(file($filename) as $line) {
		if(preg_match('/^use /', $line)) {
			$useblock[] = $line;
		} else {
			if($useblock) {
				$compare1 = implode("", $useblock);
				sort($useblock);
				$compare2 = implode("", $useblock);
				$updated = $updated || $compare1 !== $compare2;
				$block = array_merge($block, $useblock);
				$useblock = array();
			}
			$block[] = $line;
		}
	}
	
	echo $filename;
	if($updated) {
		file_put_contents($filename, implode("", $block));
		echo "\tchanged\n";
	} else {
		echo "\tunchanged\n";
	}
}

function help() {

	echo "Usage: " . basename($_SERVER['argv'][0]) . " folder [--help]\n";
	echo "\n";
	echo "The options are as follows:\n";
	echo "  -?, --help\n";
	echo "    Show this help and exit.\n\n";
}
