#!/usr/bin/python

import os, sys, stat, struct, string
import getopt

PUBLISH_DIR = os.getenv("PUBLISH_DIR")
if PUBLISH_DIR is None:
    print "Please set the environment variable 'PUBLISH_DIR'"
    sys.exit(-1)
TMD_TOOL = "%s/tmd.exe" % PUBLISH_DIR
TICKET_TOOL = "%s/ticket.exe" % PUBLISH_DIR

def Usage(msg=""):
    print "Usage: %s [-v titleVersion] -n <name> -l <content0, content1, ...>" % sys.argv[0]
    print "      -v <titleVersion>: optional title version"
    print "      -n <name>: name of the title to be published"
    print "      -l <content list>: comma separated list of contents"
    print "      -t <title ID>: specify the 64-bit title ID"
    if msg != "":
        print msg
    sys.exit(-1)

try:
    opts, args = getopt.getopt(sys.argv[1:], "dl:n:t:v:")
except getopt.GetoptError:
    Usage()

pki = "d"
titleName = ""
contentList = ""
debug = 0
titleId = 0
partner = 3L
channel = 0L
titleVersion = 0L
for o, v in opts:
    if o == '-n':
        titleName = v
    elif o == '-l':
        contentList = v
    elif o == '-t':
        titleId = long(v, 0)
    elif o == '-d':
        debug = not debug
    elif o == '-v':
        titleVersion = long(v, 0)
    
if titleName == "":
    Usage("You must specify a title name")
if len(titleName) >= 32:
    Usage("Title name must be less than 32 characters")

if titleId == 0:
  titleId =  ((((partner & 0xffff) << 16L) | (channel & 0xffff)) << 32L) | abs(hash(titleName + "titleId"))
ticketId = abs(hash(titleName + "common ticketId"))

certFile = string.replace("%s/pki/cert_%spki.sys" % (PUBLISH_DIR, pki), "\\", "/")
xsCertFile = string.replace("%s/pki/xs_%spki.cert" % (PUBLISH_DIR, pki), "\\", "/")
xsRsaFile = string.replace("%s/pki/xs_%spki.rsa" % (PUBLISH_DIR, pki), "\\", "/")
xsPubKeyFile = string.replace("%s/pki/xs_%spki.eccPubKey" % (PUBLISH_DIR, pki), "\\", "/")
xsPvtKeyFile = string.replace("%s/pki/xs_%spki.eccPvtKey" % (PUBLISH_DIR, pki), "\\", "/")
commonKeyFile = string.replace("%s/pki/common_%spki.aesKey" % (PUBLISH_DIR, pki), "\\", "/")
cpCertFile = string.replace("%s/pki/cp_%spki.cert" % (PUBLISH_DIR, pki), "\\", "/")
cpRsaFile = string.replace("%s/pki/cp_%spki.rsa" % (PUBLISH_DIR, pki), "\\", "/")
ticketFile = "%x.tik" % ticketId
tmdFile = "%x.tmd" % titleId
metaFile = "%x.meta" % titleId
open(metaFile, "wb").write(titleName)
print "ticketId = 0x%016x" % ticketId
print "titleId  = 0x%016x" % titleId

if contentList != "":
    contentList = metaFile + ',' + contentList
else:
    contentList = metaFile

contents = contentList.split(",")
cidList = ",".join(map(lambda x: "0x%08x" % abs(hash(titleName+x)), contents))
cidxList = ",".join(map(lambda x: "%d" % (x), range(len(contents))))
bootIdx = 1

tmd = '%s -O -C 1 -T %#08x -n "%s" -c "%s", -i "%s" -b %d -P c -k %s -s %s -D %s -m %d' % (TMD_TOOL, titleId, contentList, cidList, cidxList, bootIdx, commonKeyFile, cpCertFile, cpRsaFile, titleVersion)
#print tmd
os.system(tmd)

ticket = "%s -O -t %#x -T %#x -K %x.titleKey -P c -X %s -x %s -S %s -s %s" % (TICKET_TOOL, ticketId, titleId, titleId, xsCertFile, xsRsaFile, xsPubKeyFile, xsPvtKeyFile)
#print ticket
os.system(ticket)

cblobFile = "c.blob"
PADDING = 64
blob = open(cblobFile, "wb")
for cid in cidList.split(","):
    blob.write(open("%s.app" % cid[2:]).read())
    blob.write(chr(0)*((PADDING-blob.tell())%PADDING))
blob.close()
  
wad = open("%s.wad" % titleName, "wb")
wad.write(struct.pack(">i", 32))    # header size
wad.write("Is")                     # type
wad.write(struct.pack(">H", 0))     # version
for f in [certFile, "/dev/null", ticketFile, tmdFile, cblobFile, "/dev/null"]:
    wad.write(struct.pack(">I", os.stat(f)[stat.ST_SIZE]))
wad.write(chr(0)*((PADDING-wad.tell())%PADDING))

for f in [certFile, "/dev/null", ticketFile, tmdFile, cblobFile, "/dev/null"]:
    wad.write(open(f, "rb").read())
    wad.write(chr(0)*((PADDING-wad.tell())%PADDING))
wad.close()

if debug == 0:
    os.system("rm -f %s %s %s %s %x.titleKey" % (ticketFile, tmdFile, metaFile, cblobFile, titleId))
    if contentList != "":
        os.system("rm -f %s" % (" ".join(map(lambda x: "%s.app" % x[2:], cidList.split(",")))))
