#!/usr/bin/python2
# -- coding: utf-8 --

# Patch css compressed code in nickel to show all games in Beta Features for Kobo Glo Hd.

# By pipcat. Thanks to: Surquizu, GeoffR, tshering, davidfor, mobileread.com

import zlib
import os

def make_executable(path):
	mode = os.stat(path).st_mode
	mode |= (mode & 0o444) >> 2    # copy R bits to X
	os.chmod(path, mode)

def save_file(name, data) :
	f = open(name, 'wb')
	f.write(data)
	f.close()
	print 'Saved file '+name

def zipstreams(filename) :
	with open(filename, 'rb') as fh:
		data = fh.read()

	pos = 0
	found = 0

	while pos < len(data) :
		window = data[pos:pos+2]
		if window == '\x78\x9C':
			try:
				zo = zlib.decompress(data[pos:])
				if zo[0:4] == '\x89PNG':
					name = 'extraction-'+str(found)+'.png'
				elif zo[0:4] == '\x8AMNG':
					name = 'extraction-'+str(found)+'.mng'
				elif zo[0:6] == '\x3C\xB8\x64\x18\xCA\xEF':
					name = 'extraction-'+str(found)+'.qm'
				elif found < 5:
					name = 'extraction-'+str(found)+'.txt'
				else:
					name = 'extraction-'+str(found)+'.css'
					if zo.find('#sudokuContainer[qApp_deviceIsAlyssum=') != -1:
						#save_file(name, zo)

						zoco = zlib.compress(zo)
						len_zoco = len(zoco)

						if zoco == data[pos:pos+len_zoco]:
							modif = zo.replace('qApp_deviceIsTrilogy', 'qApp_deviceIsTemporary')
							modif = modif.replace('qApp_deviceIsAlyssum', 'qApp_deviceIsTrilogy')
							modif = modif.replace('qApp_deviceIsTemporary', 'qApp_deviceIsAlyssum')

							modif_compressed = zlib.compress(modif)
							if len(modif_compressed) == len_zoco:
								save_file('nickel-modif', data[:pos]+modif_compressed+data[pos+len_zoco:])
								make_executable('nickel-modif')
								print 'Ok, nickel-modif patched.'
							else:
								print 'Compressed code after modification is not the same size than original! NO patching.'
								print 'Original size: %d  New size: %d' % (len_zoco, len(modif_compressed))
						
				#save_file(name, zo)
				found += 1
			except zlib.error:
				pos = pos
		pos += 1
		if pos == len(data):
			break


zipstreams('nickel')
