import os
import glob
import zipfile

for cbz in glob.glob('**/*.cbz'):
	zin = zipfile.ZipFile(cbz, 'r')
	zout = zipfile.ZipFile(cbz+'.cbz', 'w')
	for item in zin.infolist():
		if item.filename.endswith('.acbf'):
			buffer = zin.read(item.filename).decode()
			buffer = buffer.replace(
				'<root><xmlns>http://www.acbf.info/xml/acbf/1.1</xmlns>',
				'<acbf xmlns="http://www.acbf.info/xml/acbf/1.1">'
			)
			buffer = buffer.replace('</root>', '</acbf>')
			zout.writestr('metadata.acbf', buffer.encode())
		elif not item.is_dir():
			buffer = zin.read(item.filename)
			zout.writestr(item, buffer)
	zin.close()
	zout.close()
	os.remove(cbz)

# for cbz in os.listdir():
	# if cbz.endswith('.cbz'):
		# zin = zipfile.ZipFile(cbz, 'r')
		# zout = zipfile.ZipFile(cbz+'.cbz', 'w')
		# for item in zin.infolist():
			# if item.filename.endswith('.acbf'):
				# buffer = zin.read(item.filename).decode()
				# buffer = buffer.replace(
					# '<root><xmlns>http://www.acbf.info/xml/acbf/1.1</xmlns>',
					# '<acbf xmlns="http://www.acbf.info/xml/acbf/1.1">'
				# )
				# buffer = buffer.replace('</root>', '</acbf>')
				# zout.writestr(cbz.replace('.cbz', '.acbf'), buffer.encode())
			# else:
				# buffer = zin.read(item.filename)
				# zout.writestr(item, buffer)
		# zin.close()
		# zout.close()
		# os.remove(cbz)