#!/usr/bin/perl
#
# minigrep - a very, very cheap egrep substitute for logcheck
#
# This uses Perl to emulate egrep (or grep -E).  Only the --file and
# --invert-match options (and their abbreviated forms) are supported; the
# --extended-regexp and --text options are enabled by default and ignored.
#

use 5.006;
use strict;
use warnings;

use Getopt::Long 2.24, qw(:config gnu_getopt);

my $invert;		# -v flag inverts the condition
my $file;		# filename from which to read regexes
my @re;			# list of regexes to match


sub error {
	print STDERR shift, "\n";
	exit 2;
}

sub usage {
	print STDERR "Usage: $0 [-v] { -f <file> | <pattern> } <file> ...\n";
	exit(@_ ? shift : 2);
}

# Parse whatever few options we recognize
GetOptions(
		'help|h|?'		=> sub { usage(0) },
		'file|f=s'		=> \$file,
		'invert-match|v'	=> \$invert,
		'text|a'		=> sub {},	# ignore, default
		'extended-regexp|E'	=> sub {},	# ignore, default
	) or usage;

if (defined $file) {
	open FILE, $file or error "Cannot open $file: $!";
	while (<FILE>) {
		chomp;
		push @re, qr/$_/;
	}
	close FILE;
} else {
	usage unless @ARGV;
	my $re = shift @ARGV;
	push @re, qr/$re/;
}

my $matched;

while (<>) {
	my $line = $_;
	$matched++, print if $invert xor grep { $line =~ /$_/ } @re;
}

exit($matched ? 1 : 0);

