#!/usr/bin/env python
import sys
import re
import os
import argparse

parser = argparse.ArgumentParser(description='Indent Converter')
parser.add_argument('folder', metavar="FOLDER", type=str, help='Specify folder to run')
parser.add_argument('-name', type=str, help='regex pattern to match')
group = parser.add_mutually_exclusive_group()
group.add_argument('-space', type=int, help="Specify amount of space")
group.add_argument('-tab', action='store_true', help="Specify to use tab")
parser.print_help()
args = parser.parse_args()

indent_new = " " * args.space if args.space else "\t"

last_dir = None
for root, _, files in os.walk(args.folder):
	if "node_modules" in root or "bc" in root or ".git" in root: continue
	# print '>', root
	for f in files:
		if args.name and not re.search(args.name, f):
			continue
		if not f.endswith((".js", ".ts", ".scss", ".css", ".jade", ".html", ".py")):
			continue
		fullpath = os.path.join(root, f)
		# print fullpath
		with open(fullpath, 'rb') as src:
			content = src.read()
			old_indent_re = re.compile("^(\t| {2,})(?=\S)", flags=re.M)
			init_search = old_indent_re.search(content)
			if init_search:
				indent_old = init_search.group(1)
				if indent_old == indent_new:
					continue
				if last_dir != root:
					last_dir = root
					print ">", root
				print "\t%d:[%r] %s" % (len(indent_old), indent_old, f)
				new_content = re.sub("^((?:" + indent_old + ')+)',
					lambda m: m.group(0).replace(indent_old, indent_new), content, flags=re.M)
				# print [content[:1000]]
				# print [new_content[:1000]]
				with open(fullpath, 'wb') as dst:
					dst.write(new_content)
				# break