#!/usr/bin/env php
<?php

$autoloadLocations = [
	getcwd() . '/vendor/autoload.php',
	getcwd() . '/../../autoload.php',
	__DIR__ . '/vendor/autoload.php',
	__DIR__ . '/../vendor/autoload.php',
	__DIR__ . '/../../../autoload.php',
	__DIR__ . '/../../autoload.php',
];

$loaded = false;
foreach( $autoloadLocations as $autoload ) {
	if( is_file($autoload) ) {
		require_once($autoload);
		$loaded = true;
	}
}

if( !$loaded ) {
	fwrite(STDERR, "error: failed to locate autoloader\n");
	exit(2);
}

$regs  = [];
$files = [];

$args = $argv;
array_shift($args);

$fileToggle = false;
foreach( $args as $arg ) {
	if( $fileToggle ) {
		if( !is_readable($arg) ) {
			fwrite(STDERR, "error: failed to read file '{$arg}'.\n");
			exit(2);
		}

		$files[] = $arg;
		continue;
	}

	if( $arg === '--' ) {
		$fileToggle = true;
		continue;
	}

	$regs[] = $arg;
}

if( !$regs ) {
	fwrite(STDERR, "error: no regular expressions to match against\n");
	exit(2);
}

if( !$files ) {
	fwrite(STDERR, "error: no files to examine\n");
	exit(2);
}

$exit = 0;
foreach( $files as $file ) {
	$file = realpath($file);

	$content = file_get_contents($file);
	foreach( $regs as $reg ) {
		if( @preg_match_all($reg, $content, $matches, PREG_OFFSET_CAPTURE) ) {
			$exit = 1;
			foreach( $matches as $match ) {
				$line = substr_count(substr($content, 0, $match[0][1]), "\n") + 1;
				fwrite(STDOUT, sprintf("%s:%d error: matched regex %s(%d)\n",
					$file,
					$line,
					var_export($reg, true),
					strlen($match[0][0])
				));
			}
		}

		if( preg_last_error() !== PREG_NO_ERROR ) {
			$error = "invalid regex";
			if( function_exists('preg_last_error_msg') ) {
				$error = preg_last_error_msg();
			}

			fwrite(STDERR, "regex error: {$error}\n");
			exit(2);
		}
	}
}

exit($exit);
