#!/usr/bin/python

import getopt
import sys 
import random 
import os
import struct
import stat
import array
import string
import re

#const defined by ES
ES_WAD_HEADER_SIZE=32
ES_VIEWER_TITLE_ID = 2
ES_VIEWER_TICKET_ID=2
ES_BOOT_TITLE_ID=1
ES_BOOT_TICKET_ID=1
ES_OS_TICKET_ID=3
ES_CRL_SIZE=0
ES_SYS_CHANNEL_NC = 2L
ES_SYS_CHANNEL_RVL = 1L
ES_TITLE_TYPE_NC_TITLE = 0
ES_TITLE_TYPE_NG_TITLE = 1
ES_CONTENT_TYPE_NC_EXE = 0
ES_CONTENT_TYPE_NG_EXE = 1
ES_CONTENT_SHARED = (1<<15)
ES_DEFAULT_GID = 1
ES_TITLE_ID_COMPATBOOT1 = 0x100
ES_TITLE_ID_COMPATAPP = 0x101

ROOT=os.getenv("REVOLUTION_SDK_ROOT")
print ROOT
if ROOT is None:
    ROOT=os.getenv("ROOT")
    if (re.search("RVL", ROOT)==None):
        platform = "NC"
    else: 
        platform = "RVL"
else:
    platform="PPC"

isViewer = 0
isBoot = 0
isOS = 0
common = 0
newTicketId = 0
titleName = ""
list = ""
mFile = ""
cidList=""
cidxList=""
typeList=""
limits=""
stateMode = 0
rtc = 0
acr = 0
dvd = 0
group = ES_DEFAULT_GID
genTicket = 1
debug = 0
genWad = 0
sysAccess=""
isCompatBoot = 0
isCompatApp = 0
if (platform=="RVL"): 
    channel = 0x00010000L
    pki = 'd'
    osVersion = 3
    devCertFile = "%s/usr/etc/pki_data/dev_ng_dpki.cert" % ROOT
    TMD_TOOL = "%s/usr/bin/x86/tmd" % ROOT
    TKT_TOOL = "%s/usr/bin/x86/ticket" % ROOT
    ttype = ES_TITLE_TYPE_NG_TITLE
    ctype = ES_CONTENT_TYPE_NG_EXE
elif (platform=="PPC"): 
    channel = 0x00010000L
    pki = 'd'
    osVersion = 3
    devCertFile = "\"%s/X86/bin/pki_data/dev_ng_dpki.cert\"" % ROOT
    TMD_TOOL = "\"%s/X86/bin/tmd.exe\"" % ROOT
    TKT_TOOL = "\"%s/X86/bin/ticket.exe\"" % ROOT
    ttype = ES_TITLE_TYPE_NG_TITLE
    ctype = ES_CONTENT_TYPE_NG_EXE
elif (platform=="NC"):
    channel = 0x00020000L
    pki = 'b'
    osVersion = 0
    devCertFile = "%s/usr/etc/pki_data/dev_nc_bpki.cert" % ROOT
    TMD_TOOL = "%s/usr/bin/x86/tmd" % ROOT
    TKT_TOOL = "%s/usr/bin/x86/ticket" % ROOT
    ttype = ES_TITLE_TYPE_NC_TITLE
    ctype = ES_CONTENT_TYPE_NC_EXE
sub = 0 #do not issue subscription ticket
ctypes=""

def printUsage(): 
  if platform=="RVL" or platform=="PPC":
    print "usage:  %s -n <name> [-l <elf1>,<elf2>,...] [-m <metaFile>] [-v] [-b] [-O] [-B] [-A] [-T <sharedFlag1>,<sharedFlag2>,...] [-a <cidx1>,<cidx2>...] [-P <d|b>] [-C <channel>] [-o <osVersion>] [-D <deviceCertFile>] [-R] [-V] [-S] [-c] [-t] [-L <limitCode1,limitCode2,... limit1,limit2...>] [-p] [-w <wad input files>] [-d]" % sys.argv[0]
    print "input:  -n  <titleName>: name of the title to be published "
    print "        -l  <elf1,elf2,...>: list of ELF files for the title"
    print "            do not use -l if you only want to generate ticket"       
    print "        -m  <metaFile>: meta file for the title (default to titleName)"
    print "        -v: title is IPL"
    print "        -b: title is boot"
    print "        -O: title is OS"
    print "        -B: title is compatible mode BOOT1"
    print "        -A: title is compatible mode app"
    print "        -T <sharedFlag1,sharedFlag2,...>: "
    print "            shared flag for each of the content files, default 0"
    print "            1: shared; 0: unshared"
    print "        -a: <cidx1,cidx2,...>: "
    print "            list of content indexes where the content can be "
    print "            accessed by the viewer"
    print "        -P <b|d>: type of PKI (default is 'd' development PKI)"
    print "        -C <channel>: channel # (default is 1 for boot, IPL and OS"
    print "                                 and 3 for any other titles)"
    print "        -o <osVersion>: os version (default 0 for boot, "
    print "                                    and 3 for any other titles)"
    print "        -D <devCertFile>: device cert, default  "
    if platform!="PPC":
        print "                          $ROOT/usr/etc/pki_data/dev_ng_dpki.cert"
    else:
        print "                          $REVOLUTION_SDK_ROOT/X86/bin/pki_data/dev_ng_dpki.cert"
    print "        -w <wad input files>: space delimited certFile, ticketFile,"
    print "                              tmdFile, metaFile, contentFiles  "
    print "        -R: grant title access to kernel register"
    print "        -V: grant title access to DVD"
    print "        -S: issue subscription ticket"
    print "        -c: issue common ticket"
    print "        -t: issue ticket with random ticketId than default"
    print "        -L <limitCode1,limitCode2,... limit1,limit2,...>: "
    print "            issue limited play ticket, limit codes are: "
    print "            1: duration time a title can be played, "
    print "               limit is set in units of seconds "
    print "            4: number of times a title can be launched "
    print "        -p: publish title only, do not ticket"
    print "        -d: keep output files for debugging"
    print "output: <titleName>.wad file for import" 
    print "        ticket file <ticketId>.tik"
    print "        TMD file <titleId>.tmd"
    print "        encrypted content files <cids>.app"
    sys.exit(-1)
  elif (platform=="NC"):
    print "usage:  %s -n <name> [-l <elf1>,<elf2>,...] [-m <metaFile>] [-s stateMode] [-r] [-v] [-b] [-P <b|d>] [-C <channel>] [-o <osVersion>] [D <deviceCertFile>] [-S] [-T <sharedFlag1>,<sharedFlag2>,...] [-a <cidx1>,<cidx2>...] [-c] [-t] [-L <limitCode1,limitCode2,... limit1,limit2,...>] [-p] [-d]" % sys.argv[0]
    print "input:  -n  <titleName>: name of the title to be published "
    print "        -l  <elf1,elf2,...>: list of ELF files for the title"
    print "            do not use -l if you only want to generate ticket"       
    print "        -m  <metaFile>: meta file for the title (default to titleName)"
    print "        -s  <stateMode> "
    print "            1: sram 256K"
    print "            2: flash 512K"
    print "            3: flash 1024K"
    print "            4: eerom 4K"
    print "            5: eerom 64K"
    print "        -r: title requires RTC"
    print "        -v: title is the viewer"
    print "        -b: title is boot"
    print "        -P <b|d>: type of PKI (default is 'b' beta PKI)"
    print "        -C <channel>: channel # (default is 2 for boot/OS and viewer"
    print "                                 and 3 for any other titles)"
    print "        -o <osVersion>: os version (default 0)"
    print "        -D <devCertFile>: device cert, default  "
    print "                          $ROOT/usr/etc/pki_data/dev_nc_bpki.cert"
    print "        -S: issue subscription ticket"
    print "        -T <sharedFlag1,sharedFlag2,...>: "
    print "            shared flag for each of the content files, default 0"
    print "            1: shared; 0: unshared"
    print "        -a: <cidx1,cidx2,...>: "
    print "            list of content indexes where the content can be "
    print "            accessed by the viewer"
    print "        -c: issue common ticket"
    print "        -t: issue ticket with random ticketId than default"
    print "        -L <limitCode1,limitCode2,... limit1,limit2,...>: "
    print "            issue limited play ticket, limit codes are: "
    print "            1: duration time a title can be played, "
    print "               limit is set in units of seconds "
    print "            4: number of times a title can be launched "
    print "        -p: publish title only, do not ticket"
    print "        -w <wad input files>: space delimited certFile, ticketFile,"
    print "                              tmdFile, metaFile, contentFiles  "
    print "        -d: keep output files for debugging"
    print "output: <titleName>.wad file for import using vnshell" 
    print "        ticket file <ticketId>.tik"
    print "        TMD file <titleId>.tmd"
    print "        encrypted content files <cids>.app"
    sys.exit(-1)

if (len(sys.argv)<=2):
    printUsage()

#get argments
opts, args = getopt.getopt(sys.argv[1:], "vbOctL:n:l:m:s:P:C:o:D:ST:a:rg:pw:dRVBA")
for o, v in opts: 
    if o=="-v":
        isViewer = 1
    elif o=="-b":
        isBoot = 1
    elif o=="-t":
        newTicketId = 1
    elif o=="-L":
        limits = v
    elif o=="-c":  
        common=1
    elif o=="-n":
        titleName = v
    elif o=="-P":
        pki = v
    elif o=="-C":
        channel = long(v)
    elif o=="-O":
        isOS = 1
    elif o=="-o":
        osVersion = long(v)
    elif o=="-D":
        devCertFile = v
    elif o=="-S": 
        sub = 1
    elif o=="-l": 
        list = v
    elif o=="-T": 
        typeList = v
    elif o=="-a": 
        sysAccess = v
    elif o=="-m": 
        mFile = v
    elif o=="-r": 
        rtc = 1
    elif o=="-g":
        group = int(v)
    elif o=="-s":
        stateMode = int(v)
    elif o=="-p": 
        genTicket = 0
    elif o=="-w": 
        genWad = 1
        genTicket = 0
        wfiles = v
    elif o=="-d": 
        debug = 1
    elif o=="-R": 
        acr = 1
    elif o=="-V": 
        dvd = 2
    elif o=="-B": 
        isCompatBoot = 1
    elif o=="-A": 
        isCompatApp = 1
if titleName=="":
    print "need to specify title name"
    printUsage()

if isViewer==1:
    ticketId = ES_VIEWER_TICKET_ID 
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL 
        osVersion = 3
    elif platform=="NC":
        channel = ES_SYS_CHANNEL_NC 
        osVersion = 0
    titleId = (channel<<32) | ES_VIEWER_TITLE_ID
    osVersion = (channel<<32) | osVersion 
    common = 1
elif isBoot==1:
    ticketId = ES_BOOT_TICKET_ID
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL 
        osVersion = 0
    elif platform=="NC":
        channel = ES_SYS_CHANNEL_NC 
        osVersion = 0
    titleId = (channel<<32) | ES_BOOT_TITLE_ID
    common = 1
elif isOS==1:
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL 
        ticketId = osVersion
    elif platform=="NC":
        ticketId = ES_OS_TICKET_ID
        channel = ES_SYS_CHANNEL_NC 
        osVersion = 0
    titleId = (channel<<32) | osVersion 
    osVersion = 0
    common = 1
else:
    if platform=="RVL" or platform=="PPC":
        osVersion = (ES_SYS_CHANNEL_RVL<<32) | osVersion 
        if isCompatBoot==1:
            titleId = (ES_SYS_CHANNEL_RVL << 32) | ES_TITLE_ID_COMPATBOOT1
        elif isCompatApp==1:
            titleId = (ES_SYS_CHANNEL_RVL << 32) | ES_TITLE_ID_COMPATAPP
        else:
            titleId = (channel<<32) | abs(hash(titleName+"titleId"))
    elif platform=="NC": 
        osVersion = (ES_SYS_CHANNEL_NC<<32) | osVersion 
        titleId = (channel<<32) | abs(hash(titleName+"titleId"))
    if newTicketId==1:
        ticketId = abs(hash(titleName+limits+"ticketId"+str(random.randint(0,0xffff))))
    else:
        if common==0:
            ticketId = abs(hash(titleName+limits+"individual ticketId"))
        elif common==1:
            ticketId = abs(hash(titleName+limits+"common ticketId"))
metaCid = abs(hash(titleName+"meta"))

print "ticketId = %x" % ticketId
print "titleId = %x" % titleId
print "metaCid = %08x" % metaCid

if sub==1:
    stid = titleId & 0xffffffff00000000
else:
    stid = titleId

#run "tmd"
if list!="":
    contents=list.split(",")
    print contents

    #check file suffix to be .mrg 
    for f in contents:
        if (re.search("\.mrg$", f)==None):
            if (re.search("\.img$", f)==None):
                print "Error: file must have .mrg or .img suffix\n"
                sys.exit(-1)
    
    if platform=="NC":
        #check viewer size 
        if isViewer==1:
            st = os.stat(contents[0])
            if st[stat.ST_SIZE]>2*1024*1024: 
                print "Error: viewer size is larger than 2M\n"
                sys.exit(-1)

    cidList = "".join(map(lambda x: "0x%08x," % abs(hash(titleName+x)), contents))[:11*len(contents)-1]
    cidxList = "0" + "".join(map(lambda x: ",%d" % (x+1), range(len(contents)-1)))
    if typeList=="": 
        ctypes = ",".join(map(lambda x: "0x%x"%ctype, range(len(contents))))
    else:
        ctypes = ",".join(map(lambda x: "0x%x"%((int(x)<<15)|ctype), typeList.split(",")))

    if platform=="NC":
        rights = (rtc<<3) | (stateMode)
    elif platform=="RVL" or platform=="PPC":
        rights = (dvd | acr)

    if sub==1: 
        tmd = "%s -O -S -T 0x%x" % (TMD_TOOL, stid) 
        print tmd
        os.system(tmd)
        tmd = "%s -O -S -C 0x%x -t \"%s\" -o 0x%x -K %x.titleKey -T 0x%x -n \"%s\" -c \"%s\" -i \"%s\" -b 0 -r 0x%08x -g 0x%x -P %s" % (TMD_TOOL, ttype, ctypes, osVersion, stid, titleId, list, cidList, cidxList, rights, group, pki) 
    else: 
        tmd = "%s -O -C 0x%x -t \"%s\" -o 0x%x -T 0x%x -n \"%s\" -c \"%s\" -i \"%s\" -b 0 -r 0x%08x -g 0x%x -P %s" % (TMD_TOOL, ttype, ctypes, osVersion, titleId, list, cidList, cidxList, rights, group, pki) 
    print tmd
    os.system(tmd)

#run "ticket"
if genTicket==1:
    if (sysAccess!=""):
        sysAccess = "-a %s" % sysAccess
    if limits!="": 
        lc = limits.split(" ")[0]
        l = limits.split(" ")[1]
        limits = "-L %s -l %s" % (lc, l)
    if common==1:
        ticket = "%s -O -t 0x%x -T 0x%x -K %x.titleKey -P %s %s %s" % (TKT_TOOL, ticketId, stid, stid, pki, limits, sysAccess)
    elif common==0:
        ticket = "%s -O -t 0x%x -T 0x%x -K %x.titleKey -i -D %s -P %s %s %s" % (TKT_TOOL, ticketId, stid, stid, devCertFile, pki, limits, sysAccess)
    print ticket
    os.system(ticket)

#output .wad file
if genWad==1: 
    certFile = wfiles.split(" ")[0]
    ticketFile = wfiles.split(" ")[1]
    tmdFile = wfiles.split(" ")[2]
    metaFile = wfiles.split(" ")[3]
    contentFiles = wfiles.split(" ")[4:]
else:
    if platform=="PPC":
        certFile = "%s/X86/bin/pki_data/cert_%spki.sys" % (ROOT, pki)
    else:
        certFile = "%s/usr/etc/pki_data/cert_%spki.sys" % (ROOT, pki)
    ticketFile = "%x.tik" % ticketId
    tmdFile = "%x.tmd" % titleId 
    metaFile = "%08x.met" % metaCid

if list!="": 
    if mFile=="": 
        fd = open(metaFile, "wb")
        if isBoot!=1: 
            fd.write(titleName)
        fd.close()
    else:
        os.system("cp %s %s" % (mFile, metaFile))

#### publish title and ticket
if (list!="" and genTicket==1) or (genWad==1): 
    sizeFile = open("wad.head", "wb")
    sizeFile.write(struct.pack('>i', ES_WAD_HEADER_SIZE)) #hard code ESWadHeader size
    sizeFile.seek(8) #skip ESWadHeader.contentOffset
    contentOffset = ES_WAD_HEADER_SIZE
    for f in [certFile, ticketFile, tmdFile, metaFile]:
        st = os.stat(f)
        print "size:%d" % st[stat.ST_SIZE]
        contentOffset += st[stat.ST_SIZE]
        sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
    sizeFile.write(struct.pack('>i', metaCid))
    sizeFile.write(struct.pack('>i', ES_CRL_SIZE)) 
    padding = 64 - contentOffset%64
    if padding!=64:
        contentOffset+= padding
    sizeFile.seek(4) #write ESWadHeader.contentOffset
    sizeFile.write(struct.pack('>i', contentOffset))
    sizeFile.close()
    padFile = open("pad.tmp", "wb")
    if padding!=64:
        for i in range(padding):
            padFile.write(struct.pack('x'))
    padFile.close()
    if genWad!=1: 
        catCmd = "cat wad.head \"%s\" %s %s %s pad.tmp %s > %s.wad" % (certFile, ticketFile, tmdFile, metaFile, " ".join(map(lambda x: "%s.app" % x[2:], cidList.split(","))), titleName)
    else:
        catCmd = "cat wad.head \"%s\" %s %s %s pad.tmp %s > %s.wad" % (certFile, ticketFile, tmdFile, metaFile, " ".join(map(lambda x: "%s" % x[0:], contentFiles)), titleName)
#### publish title only
elif list!="" and genTicket==0: 
    sizeFile = open("wad.head", "wb")
    sizeFile.write(struct.pack('>i', ES_WAD_HEADER_SIZE)) #hard code ESWadHeader size
    sizeFile.seek(8) #skip ESWadHeader.contentOffset
    contentOffset = ES_WAD_HEADER_SIZE
    for f in [certFile, ticketFile, tmdFile, metaFile]:
        if f!=ticketFile:
            st = os.stat(f)
            print "size:%d" % st[stat.ST_SIZE]
            sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
            contentOffset += st[stat.ST_SIZE]
        else:
            print "size:0"
            sizeFile.write(struct.pack('>i', 0))
    sizeFile.write(struct.pack('>i', metaCid))
    sizeFile.write(struct.pack('>i', ES_CRL_SIZE)) 
    padding = 64 - contentOffset%64
    if padding!=64:
        contentOffset+= padding
    sizeFile.seek(4) #write ESWadHeader.contentOffset
    sizeFile.write(struct.pack('>i', contentOffset))
    sizeFile.close()
    padFile = open("pad.tmp", "wb")
    if padding!=64:
        for i in range(padding):
            padFile.write(struct.pack('x'))
    padFile.close()
    catCmd = "cat wad.head %s %s %s pad.tmp %s > %s.wad" % (certFile, tmdFile, metaFile, " ".join(map(lambda x: "%s.app" % x[2:], cidList.split(","))), titleName)
#### publish ticket only
elif list=="" and genTicket==1:
    sizeFile = open("wad.head", "wb")
    sizeFile.write(struct.pack('>i', ES_WAD_HEADER_SIZE)) #hard code ESWadHeader size
    sizeFile.write(struct.pack('>i', 0)) #contentOffset 0 means no content
    for f in [certFile, ticketFile]:
        st = os.stat(f)
        print "size:%d" % st[stat.ST_SIZE]
        sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
    sizeFile.write(struct.pack('>i', 0)) #tmd size
    sizeFile.write(struct.pack('>i', 0)) #meta size
    sizeFile.write(struct.pack('>i', 0)) #meta cid
    sizeFile.write(struct.pack('>i', ES_CRL_SIZE)) 
    sizeFile.close()
    catCmd = "cat wad.head %s %s > %s.wad" % (certFile, ticketFile, titleName)

print catCmd
os.system(catCmd)
os.system("rm wad.head")
os.system("rm pad.tmp")
if debug==0:
    os.system("rm %s %s %s %x.titleKey" % (ticketFile, tmdFile, metaFile, stid))
    if list!="": 
        os.system("rm %s" % (" ".join(map(lambda x: "%s.app" % x[2:], cidList.split(",")))))

