<?php 
	$directory = "."; // the directory the script runs on (recursively) without final the final slash (/)
	$mail_to = "your-email@example.com"; // whom to mail when stuff's been modified
	$mail_from = "noreply@example.com"; // because mailservers require a from address...
	$verbose = true; // Verbose output. Useful when you're debugging or running from a command line.
	
	error_reporting(~E_NOTICE);
	
	// Load existing file hashes if available
	if (file_exists("hashes.txt")) {
		if ($verbose)
			echo microtime(true) . " Loading hashes.txt\n";
		
		$first_run = false;
		
		$existing_hashes = explode("\n", file_get_contents("hashes.txt"));
		foreach ($existing_hashes as $key=>$hash) {
			$tmp = explode(" ", $hash);
			$existing_hashes[$tmp[0]] = $tmp[1];
			unset($existing_hashes[$key]);
		}
	}
	else {
		if ($verbose)
			echo microtime(true) . " No existing hashes.txt - first run\n";
		
		$first_run = true;
	}
	
	// 
	$file_hashes = "";
	function parsedir($dir) {
		global $file_hashes, $existing_hashes, $first_run, $verbose;
		
		if ($verbose)
			echo microtime(true) . " Parsing dir $dir\n";
		
		$d = opendir($dir);
		while ($f = readdir($d)) {
			if ($f == "." || $f == ".." || $f == "hashes.txt" || $f == "uh-oh.txt")
				continue;
			
			if (is_dir($dir . "/" . $f)) {
				parsedir($dir . "/" . $f);
			}
			else {
				if ($verbose)
					echo microtime(true) . " Handling file $dir/$f\n";
				
				$path_hash = md5($dir . "/" . $f);
				$file_hash = md5(file_get_contents($dir . "/" . $f));
				if (!$first_run || isset($existing_hashes[$path_hash])) {
					if ($existing_hashes[$path_hash] != $file_hash) {
						$new_file = empty($existing_hashes[$path_hash]);
						
						if ($verbose)
							if ($new_file)
								echo microtime(true) . " New file: $dir/$f\n\n";
							else
								echo microtime(true) . " Trouble in $dir/$f: Hash\n" . $existing_hashes[$path_hash] . " doesn't match\n" . $file_hash . "\n\n";
						
						$fid = fopen("uh-oh.txt", "a");
						fwrite($fid, date("r") . ": " . ($new_file ? "New file: " : "") . $dir . "/" . $f . "\r\n");
						fclose($fid);
					}
					else {
						if ($verbose)
							echo microtime(true) . " $dir/$f passed\n";
					}
				}
				$file_hashes .=  $path_hash . " " . $file_hash . "\n";
			}
		}
	}
	
	parsedir($directory);
	
	if ($verbose)
		echo microtime(true) . " Writing hashes.txt\n";
	
	$fid = fopen("hashes.txt", "w");
	fwrite($fid, $file_hashes);
	fclose($fid);
	
	if (file_exists("uh-oh.txt")) {
		if ($verbose)
			echo microtime(true) . " Sending uh-oh email\n";
		
		mail($mail_to, "File modified on server", file_get_contents("uh-oh.txt"), "From: $mail_from") or die("uh-oh");
	}
	
	if ($verbose)
		echo microtime(true) . " done\n";