#!/usr/bin/env python
# by Hye-Shik

import os, re
import glob, sys

TTX_CMD='ttx'
BSDIFF_CMD='bsdiff'

re_xmlcharref = re.compile('&#([0-9]{1,5});')

def fixutf8charref(s):
	try:
		u = re_xmlcharref.sub(lambda x: chr(int(x.groups()[0])), s)
	except ValueError:
		return s

	try:
		u = u.decode('utf-8')
	except UnicodeDecodeError:
		return s
	else:
		fixed = u.encode('us-ascii', 'xmlcharrefreplace')
		if fixed != s:
			print "From:", s
			print "To:", fixed
			fixutf8charref.modified = True
			return fixed
		else:
			return s

def fixenc(f):
	print "Checking %s..." % f
	ttxname = f.replace('.ttf', '.ttx')
	if os.access(ttxname, 0):
		os.unlink(ttxname)
	os.system('%s -t name %s' % (TTX_CMD, f))
	ttxtxt = file(ttxname).read()
	fixutf8charref.modified = False
	ttxtxt = '\n'.join(map(fixutf8charref, ttxtxt.splitlines()))
	if fixutf8charref.modified:
		print " ==> Wrongly Encoded"
	else:
		print " ==> Okay"
		return

	print "Fixing %s..." % f
	file(ttxname, 'w').write(ttxtxt)
	tmpfname = f.replace('.ttf', '#1.ttf')
	if os.access(tmpfname, 0):
		os.unlink(tmpfname)
	os.system('%s -m %s %s' % (TTX_CMD, f, ttxname))
	print " ==> Done"

	print "Generating BSDiff for %s..." % f
	diffname = f.replace('.ttf', '-ooofontname.diff')
	os.system('%s %s %s %s' % (BSDIFF_CMD, f, tmpfname, diffname))
	os.unlink(tmpfname)
	print " ==> Done"

if __name__ == '__main__':
	for f in glob.glob('*.ttf'):
		fixenc(f)

