#!/usr/bin/python2.7
# -*- coding: utf-8 -*-

from __future__ import print_function

import os
import re
import sys
import tempfile
import subprocess

EXECUTE_TOKEN = re.compile('@!@')


futurize_args = [
	'-f', 'libfuturize.fixes.fix_print_with_import',
	'-f', 'libfuturize.fixes.fix_raise',
	'-f', 'lib2to3.fixes.fix_throw',
	'-f', 'lib2to3.fixes.fix_sys_exc',
	'-f', 'lib2to3.fixes.fix_map',
	'-f', 'lib2to3.fixes.fix_isinstance',
	'-f', 'lib2to3.fixes.fix_has_key',  # problematic due to UDM?
	'-f', 'lib2to3.fixes.fix_exec',
	'-f', 'lib2to3.fixes.fix_except',
]


def migrate(name):
	with open(name, 'rb') as fd:
		template = fd.read()
	while True:
		i = EXECUTE_TOKEN.finditer(template)
		try:
			start = next(i)
			end = next(i)

			value = template[start.end():end.start()]
			with tempfile.NamedTemporaryFile(suffix='.py') as fd:
				fd.write(value)
				fd.flush()
				try:
					with open(os.devnull) as devnull:
						subprocess.check_call(['futurize', '-wn', '--no-diffs'] + futurize_args + [fd.name], stdout=devnull, stderr=subprocess.STDOUT, close_fds=True)
				except subprocess.CalledProcessError:
					print('futurize failed for %s' % (name,), file=sys.stderr)
					return
				value = open(fd.name, 'rb').read()
				value = value.replace('from __future__ import print_function\n', '')
			template = template[:start.start()] + '@!3@' + value + '@!3@' + template[end.end():]
			with open(name, 'wb') as fd:
				fd.write(template)
		except StopIteration:
			break
		with open(name, 'rb') as fd:
			new_template = fd.read().replace('@!3@', '@!@')
		with open(name, 'wb') as fd:
			fd.write(new_template)


if __name__ == '__main__':
	files = subprocess.check_output("find */*/conffiles -type f  -exec grep -l -F '@!@'  {} +", shell=True, close_fds=True).splitlines()
	for filename in files:
		migrate(filename)
