"""
Copyright (c) 2006, Jari Sukanen
All rights reserved.

Redistribution and use in source and binary forms, with or 
without modification, are permitted provided that the following 
conditions are met:
	* Redistributions of source code must retain the above copyright 
	  notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright 
	  notice, this list of conditions and the following disclaimer in 
	  the documentation and/or other materials provided with the 
	  distribution.
    * Names of the contributors may not be used to endorse or promote 
	  products derived from this software without specific prior written 
	  permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
"""
from sis import sisinfo, sisfields
import optparse
import sys, os

APP_PATH = "epoc32" + os.sep + "apps"
IBY_PATH = "epoc32" + os.sep + "rom" + os.sep + "include"
CRLF = '\r\n'

try:
	os.uname()
	ZIP_CMD = 'zip -r '
except: # no uname on windows
	ZIP_CMD = '7z a '

PyASN1Availabe = True

try :
    from pyasn1.codec.der import decoder
    from pyasn1.type import univ, base
except :
    PyASN1Availabe = False

def _findItem(item, itemParent, index, objectIdentifier) :
	if isinstance(item, base.AbstractSimpleAsn1Item) :
		if item == objectIdentifier :
			return itemParent[index+1]
	else :
		for i in range(len(item)) :
			found = _findItem(item[i], item, i, objectIdentifier)
			if found : 
				return found

def findItem(decodedCert, objectIdentifier) :
	return _findItem(decodedCert, None, 0, objectIdentifier)


class CertificateOrganization :
	def __init__(self) :
		pass
	
	def parse(self, decodedCert) :
		self.commonName = findItem(decodedCert, (2,5,4,3))
		self.countryCode = findItem(decodedCert, (2,5,4,6))
		self.locality = findItem(decodedCert, (2,5,4,7))
		self.state = findItem(decodedCert, (2,5,4,8))
		self.street = findItem(decodedCert, (2,5,4,9))
		self.organization = findItem(decodedCert, (2,5,4,10))

	def readableStr(self) :
		buf = ""
		if self.commonName :
			buf += self.commonName.prettyPrint() + "\n"
		if self.countryCode :
			buf += self.countryCode.prettyPrint() + "\n"
		if self.locality :
			buf += self.locality.prettyPrint() + "\n"
		if self.state :
			buf += self.state.prettyPrint() + "\n"
		if self.street :
			buf += self.street.prettyPrint() + "\n"
		if self.organization :
			buf += self.organization.prettyPrint()
		return buf
		
class CertificateInfo :
	def __init__(self) :
		pass
		
	def parse(self, decodedCert) :
		self.issuer = CertificateOrganization()
		self.issuer.parse(decodedCert[0][3])
		
		self.signer = CertificateOrganization()
		self.signer.parse(decodedCert[0][5])
		
	def readableStr(self) :
		buf = "Signer:\n      " + "\n      ".join(self.signer.readableStr().split('\n')) + "\n"
		buf += "Issuer:\n      " + "\n      ".join(self.issuer.readableStr().split('\n')) + "\n"
		return buf
			

class Handler :
    def __init__(self) :
		self.files = []
		self.fileDatas = []
		self.signatureCertificateChains = []
		
    def handleField(self, field, depth) :
		if field.type == sisfields.FileDescriptionField :
			self.files.append(field)
		elif field.type == sisfields.FileDataField :
			self.fileDatas.append(field)
		elif field.type == sisfields.SignatureCertificateChainField  :
			self.signatureCertificateChains.append(field)

    def print_iby_for_file(self, iby, extracted_file, install_path):
    	#binarypath="file=ABI_DIR\\BUILD_DIR\\"
    	#datapath="data=DATAZ_\\RESOURCE_FILES_DIR\\"
    	binarypath="file=\\"
    	datapath="data=\\"
    	#privatepath="data=\\epoc32\\data\\z\\"
    	
    	install_path=install_path.replace('c:', 'z:')
    	#basename = filepath[filepath.rfind('\\')+1:]
    	
    	if extracted_file.endswith('exe') or extracted_file.endswith('dll'):
    		iby.write( binarypath + extracted_file + '\t\t' + install_path + CRLF)
    	else:
    		iby.write( datapath + extracted_file + '\t\t' + install_path + CRLF)

    	
    def execute(self,outputname, iby) :
        for f in self.files :
			buf = f.findField(sisfields.StringField)[0].readableStr()
#			caps = f.findField(sisfields.CapabilitiesField)[0]
#			if caps :
#				buf += " [" + " ".join(f.findField(sisfields.CapabilitiesField)[0].readableCaps) + "]"
			
			install_path=buf
			parts = f.findField(sisfields.StringField)[0].readableStr().split("\\")
			#for part in parts:
			#	print part
			if len(parts[len(parts) - 1]) > 0 :
				path = os.getcwd() + os.sep + APP_PATH
				
				path += os.sep + os.sep.join(parts[1:-1])
				rel_file = APP_PATH + os.sep + outputname + os.sep + os.sep.join(parts[1:])
				rel_file = rel_file.replace('/','\\')
				if not os.path.exists(path) :
					os.makedirs(path)
				extracted_file = path + os.sep + parts[len(parts) - 1]
				newFile = file(extracted_file, "wb")
				newFile.write(self.fileDatas[f.fileIndex].findField(sisfields.CompressedField)[0].data)
				newFile.close()
				self.print_iby_for_file(iby,rel_file, install_path)
			
class ContentPrinter :
	def __init__(self) :
		pass
		
	def handleField(self, field, depth) :
		buf = ""
		for i in range(depth) :
			buf += "  "
		buf += sisfields.FieldNames[field.type] + " "
		if len(field.readableStr()) > 0 :
			buf += field.readableStr()
		print buf

import pdb
    
if __name__ == "__main__" :
	if len(sys.argv) == 1:
		print "usage: %s <sisfile>" % sys.argv[0]
		exit()
		
	sisname = sys.argv[1]
	sisInfo = sisinfo.SISInfo()
	sisInfo.parse(sisname)
	
	handler = Handler()
	sisInfo.traverse(handler)
	
	tmp = sisname.lower()
	
	if tmp.find(os.sep):
		tmp = sisname[sisname.rfind(os.sep)+1:]
	
	if tmp.find('sisx'):
		tmp = tmp[0:len(tmp)-4]
	elif tmp.find('sis'):
		tmp = tmp[0:len(tmp)-3]
	
	iby_path = os.getcwd() + os.sep + IBY_PATH + os.sep
	iby_file = tmp + ".iby"
	
	if not os.path.exists(iby_path) :
		os.makedirs(iby_path)
					
	iby = open(iby_path + iby_file,'w')
	print "Creating IBY file..."
	iby.write( "#ifndef __%s_IBY__" % tmp.upper() + CRLF)
	iby.write( "#define __%s_IBY__" % tmp.upper() + CRLF)
	print "Extracting SIS..."
	handler.execute(tmp, iby)
	iby.write( "#endif" + CRLF)
	iby.close()
	print "Zipping..."
	os.system(ZIP_CMD + tmp + '.zip epoc32')
	print "All done. Remember to #include <%s> in your main IBY file" % iby_file