from __future__ import print_function
import sys
import re
import glob
import argparse


def eprint(*args, **kwargs):
	# Print to STDERR instead of STDOUT
    print(*args, file=sys.stderr, **kwargs)


def grep(expression, filepath, ignorecase=False, invert=False):
	raw_expression = re.escape(expression)
	with open(filepath) as file:
		for line in file:
			# Enable case matching?
			if ignorecase:
				matches = re.search(raw_expression, line, re.I)
			else:
				matches = re.search(raw_expression, line)

			# Invert matches if need be and print
			if matches and not invert:
				print(line)
			elif invert and not matches:
				print(line)


def main():
	parser = argparse.ArgumentParser(description='This is a pure Python based clone of the GREP command')
	parser.add_argument('expression', action="store", type=str, help="Regular expression to match against")
	parser.add_argument('filepath', action="store", type=str, help="Path to file to search in. supports wildcard globs")
	parser.add_argument('-i', action="store_true", default=False, dest="ignorecase", help="Ignore case")
	parser.add_argument('-v', action="store_true", default=False, dest="invert", help="Show lines that don't match")
	args = parser.parse_args()
	
	file_list = glob.glob(args.filepath)
	for f in file_list:
		if len(file_list) > 1:
			eprint("\nResults for file: %s" % f)
			eprint("-"*(len(f)+18))
		grep(args.expression, f, ignorecase=args.ignorecase, invert=args.invert)


if __name__ == '__main__':
	main()
