#!/usr/bin/env python3
'''
	This script temporary change all fields to public
	This purpose is to let the signed code to compile
	Once the dll is complied, revert the code in git
'''

import os
import sys
import re
from tempfile import mkstemp
from shutil import move

types = "(class|enum|interface|delegate)"

pubType = re.compile( r".+public (\w+ )?" + types )
priType = re.compile( r".+private (\w+ )?" + types )
intType = re.compile( r".+internal (\w+ )?" + types )
sealed = re.compile( ".+sealed.+" )
typeMatch = re.compile( r"[\s\t]+(internal )?(sealed )?(partial )?(abstract |static )?" + types )
Comment = re.compile( "^[ 	]+/[\*/]" )
typeSub = re.compile( "(|sealed )(|partial )(|static )" + types )
typeIntSub = re.compile( "internal (|sealed)(|partial )(abstract |static )" + types )

intOnly = re.compile( "^([ 	]+)(internal) (.+)" )
intProps = re.compile( ".+internal (set|get)" )

def ClassToPublic( dirName, fileName ):

	source = os.path.join( dirName, fileName )

	'''
	if "DateTimeFormatHelper" not in source:
		return
	'''
	# '''

	f = open( source )
	fh, target = mkstemp()

	f2 = open( target, "w" )

	for line in f:

		if intOnly.match( line ) is not None:

			if intProps.match( line ) is None:
				f2.write( intOnly.sub( r"\1 /*_Internal_*/ public \3", line ) )
			else:
				f2.write( line.replace( "internal",  "/*_Internal_O_*/" ) )

			continue

		if ( typeMatch.match( line ) is not None
			and Comment.match( line ) is None ):

			if ( priType.match( line ) is None
				and pubType.match( line ) is None ):

				if intType.match( line ) is None:
					f2.write( typeSub.sub( r"/*_TMP_PUB_*/ public \1\2\3\4", line ) )
				else:
					f2.write( typeIntSub.sub( r"/*_Internal_*/ public \1\2\3\4", line ) )
				continue

		f2.write( line )

	f.close()
	f2.close()

	print( source )
	'''
	with( open( target ) ) as f:
		print( f.read() )
	'''
	move( source, os.path.join( dirName, "__" + fileName ) )
	move( target, source )
	# '''

def Restore( dirName, fileName ):

	target = os.path.join( dirName, fileName[2:] )
	print( "Restore: " + target )

	os.remove( target )
	move( os.path.join( dirName, fileName ), target )

revert = False
if 1 < len( sys.argv ):
	revert = sys.argv[1] == "r"

if revert:
	for root, dirs, files in os.walk( "." ):
		for file in files:
			if file.startswith( "__" ):
				Restore( root, file )
else:
	for root, dirs, files in os.walk( "." ):
		for file in files:
			if ( file.endswith( ".cs" )
				and not file.endswith( ".g.cs" )
				and not file.endswith( ".i.cs" )
				and not file.startswith( "TemporaryGeneratedFile" ) ):
				ClassToPublic( root, file )