#!/usr/bin/python
#
# Strip code enclosed in #ifdef COMMERCIAL_CODE

import sys
import os


STRIP_FILE_EXTENSIONS= [".c", ".h", ".cc", ".cpp", ".cxx", ".m", ".mm", ".cs"]

def strip_file(file):
	lines= open(file, "r").readlines()
	nlines= []
	changed= False
	skipping= False
	ifdef= None
	inner_ifdefs= 0
	for line in lines:
		l= line.strip()
		if l and l[0] == "#":
			if l.startswith("#ifdef COMMERCIAL_CODE") or l.startswith("#if COMMERCIAL_CODE"):
				if ifdef is not None:
					print "Nested #ifdef COMMERCIAL_CODE in ",file
					sys.exit(1)
				changed= True
				ifdef= inner_ifdefs
				skipping= True
			elif l.startswith("#ifndef COMMERCIAL_CODE"):
				print "#ifndef COMMERCIAL_CODE is not allowed, but exists in", file
				sys.exit(1)

			if ifdef is not None:
				if l.startswith("#ifdef") or l.startswith("#ifndef") or l.startswith("#if"):
					inner_ifdefs+=1
				elif l.startswith("#else"):
					if inner_ifdefs == ifdef+1:
						skipping= not skipping
						continue
				elif l.startswith("#endif"):
					inner_ifdefs-=1
					if inner_ifdefs == ifdef:
						ifdef= None
						skipping= False
						continue

		if not skipping:
			nlines.append(line)
	
	if changed:
		f= open(file, "w+")
		f.write("".join(nlines))
		f.close()
		print "Stripped file %s (%i lines left)"%(file, len(nlines))


def process_directory(path):
	files= os.listdir(path)
	for file in files:
		fpath= os.path.join(path, file)
		if os.path.isdir(fpath):
			process_directory(fpath)
		elif os.path.isfile(fpath):
			if os.path.splitext(fpath)[1].lower() in STRIP_FILE_EXTENSIONS:
				strip_file(fpath)



if os.path.isdir(sys.argv[1]):
	process_directory(sys.argv[1])
else:
	strip_file(sys.argv[1])


