#!/usr/bin/python

import os
import sys
import time
sys.path.insert(0, os.path.expanduser('~/lib'))
import readline0

svn_directories = set()

directories = {}

for file in readline0.readline0():
	if file.endswith('/.svn'):
		initial = file[:-5]
		# How PowerShell'ish :-S
		svn_directories |= set((initial,))
	elif '/.svn/' in file:
		pass
	elif os.path.isfile(file):
		dir, file = os.path.split(file)
		if dir in directories:
			directories[dir].append(file)
		else:
			directories[dir] = [ file ]

# .keys to get a list, so we don't get an error about changing a dictionary we're iterating over
for dir in directories.keys():
	if dir in svn_directories:
		pass
	else:
		del directories[dir]

dirkeys = directories.keys()
dirkeys.sort()

#print 'svn_directories is', svn_directories
#print 'checking',dirkeys

def get_license_from_user():
	licenses = [ \
		'No-license', \
		'UCI-UCI', \
		'GPLv2-Stromberg', \
		'GPLv3-Stromberg', \
		'Apache2-Stromberg', \
		'MSPL-Microsoft', \
		]
	tty_file = open('/dev/tty', 'r')
	selected_index = -1
	while selected_index < 0 or selected_index >= len(licenses):
		for ind, name in enumerate(licenses):
			print '%d) %s' % (ind, name)
		selected_index = int(tty_file.readline())
	tty_file.close()
	return licenses[selected_index]

#def prop_change(directory, license):
#	# this is really the current text minus the COPYING external, if any
#	current_text_pipe = os.popen('svn propget svn:externals "%s" | egrep -v \'\\<COPYING$\'' % directory, 'r')
#	current_text = current_text_pipe.readlines()
#	current_text_pipe.close()
#	print 'got text'
#	print current_text
#	new_text = current_text[:]
#	new_text.append('http://stromberg.dnsalias.org/svn/licenses/%s COPYING\n' % license)
#	output_text_pipe = os.popen('svn propset svn:externals "%s" "%s" 2> /tmp/errors' % (''.join(new_text), directory), 'w')
#	for line in new_text:
#		output_text_pipe.write(line)
#	# give the subcommand time to complete
#	time.sleep(2)
#	output_text_pipe.close()
#	print 'wrote text'

def prop_change(directory, license):
	# this is really the current text minus the COPYING external, if any
	current_text_pipe = os.popen('svn propget svn:externals "%s" | egrep -v \'\\<COPYING$\'' % directory, 'r')
	current_text = current_text_pipe.readlines()
	current_text_pipe.close()
	new_text = current_text[:]
	new_text.append('http://stromberg.dnsalias.org/svn/licenses/%s COPYING\n' % license)
	output_text_file = open('/tmp/externals', 'w')
	for line in new_text:
		output_text_file.write(line)
	output_text_file.close()
	# give the subcommand time to complete
	os.system('svn propset svn:externals --file /tmp/externals "%s" 2> /tmp/errors' % directory)

for dirkey in dirkeys:
	if directories[dirkey] and 'COPYING' not in directories[dirkey]:
		print
		print dirkey
		license = get_license_from_user()
		print license
		prop_change(dirkey, license)
		print