#!/usr/bin/php
<?php

if(count($argv) < 2)
    die(
"Usage:\n  ".$argv[0]." path [regexp]\n");
$path $argv[1];
$pattern count($argv) < "/.*/" $argv[2];

$files preg_ls($pathtrue$pattern);
$hashes = array();
$duplicates = array();

foreach(
$files as $file){
    
$hash sha1_file($file);
    if(
array_key_exists($hash$hashes))
        
$duplicates[] = array($hashes[$hash], $file);
    else
        
$hashes[$hash] = $file;
}

print(
"Duplicates:\n");
foreach(
$duplicates as $duplicate){
    print(
"    ".$duplicate[1]." is a duplicate of ".$duplicate[0]."\n");
}

/*
 * Helper function to enumerate interesting files:
 */
function preg_ls ($path="."$rec=false$pat="/.*/") {
    
$pat=preg_replace ("|(/.*/[^S]*)|s""\\1S"$pat);
    while (
substr ($path,-1,1) =="/"$path=substr ($path,0,-1);
    if (!
is_dir ($path) ) $path=dirname ($path);
    if (
$rec!==true$rec=false;
    
$d=dir ($path);
    
$ret=Array ();
    while (
false!== ($e=$d->read () ) ) {
        if ( (
$e==".") || ($e=="..") ) continue;
        if (
$rec && is_dir ($path."/".$e) ) {
            
$ret=array_merge ($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        if (!
preg_match ($pat,$e) ) continue;
        
$ret[]=$path."/".$e;
    }
    return (empty (
$ret) && preg_match ($pat,basename($path))) ? Array ($path."/") : $ret;
}
?>