#!/usr/bin/php
<?php

echo 'Multiple file replace | by Ashus'."\n\n"
	.'Recursive [y/N]: ';
$fp = fopen("php://stdin","r");
$in = fgetc($fp);
$recursive = (strtolower($in) == 'y');
echo ' '.(($recursive)?'yes':'no')."\n";

echo 'Files matching [*]: ';
$fp = fopen("php://stdin","r");
$in = trim(fgets($fp, 1024));
if ($in == '')
	$in = '*';
$fnmatch = $in;

$in = '';
while ($in == '') {
	echo 'Search: ';
	$fp = fopen("php://stdin","r");
	$in = rtrim(fgets($fp, 1024),"\n");
}
$search = $in;

echo 'Replace: ';
$fp = fopen("php://stdin","r");
$in = rtrim(fgets($fp, 1024),"\n");
$replace = $in;

function replaceInFile($fn, $search, $replace) {
	$s = file_get_contents($fn);
    $out = str_replace($search, $replace, $s);
	if ($s!=$out) {
		file_put_contents($fn, $out);
		return true;
	}
	return false;
}

function globRecursive($path, $find) {
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if (substr($file, 0, 1) == '.') continue;
        $rfile = "{$path}/{$file}";
        if (is_dir($rfile)) {
            foreach (globRecursive($rfile, $find) as $ret) {
                yield $ret;
            }
        } else {
            if (fnmatch($find, $file))
				yield $rfile;
        }
    }
    closedir($dh);
}

if ($recursive) {
    foreach (globRecursive('.',$fnmatch) as $fn) {
    	if (replaceInFile($fn, $search, $replace))
			echo $fn."\n";
    }
} else {
    foreach (glob('./'.$fnmatch) as $fn) {
    	if (replaceInFile($fn, $search, $replace))
			echo $fn."\n";
    }
}
echo "\n";
?>