#!/usr/bin/python

import getopt
import sys
import random
import os
import struct
import stat
import array
import string
import re
from time import strftime, gmtime

VERSION_MAJOR=1
VERSION_MINOR=2

#const defined by ES
WAD_HEADER_SIZE=32      #IRD's wad format; ES_WAD_HEADER_SIZE is for BroadOn's wad format
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_RVL = 1L
ES_TITLE_TYPE_NG_TITLE = 1
ES_TITLE_TYPE_STREAM = 4
ES_TITLE_TYPE_DATA = 8
ES_CONTENT_TYPE_NG_EXE = 1
ES_CONTENT_SHARED = (1<<15)
ES_DEFAULT_GID = 2
ES_TITLE_ID_COMPATBOOT1 = 0x100
ES_TITLE_ID_COMPATAPP = 0x101

UNAME=os.uname()
if re.match("^CYGWIN", UNAME[0]):
    HOST="x86"
else:
    HOST="linux"

ROOT=os.getenv("REVOLUTION_SDK_ROOT")
if ROOT is None:
    ROOT=os.getenv("ROOT")
    if (re.search("RVL", ROOT)==None):
        print "Unknown platform. Please make sure to set NG's $ROOT or $REVOLUTION_SDK_ROOT."
        sys.exit(-1)
    else:
        platform = "RVL"
else:
    platform="PPC"

if (platform=="PPC"):
    DD_CYGWIN = "iflag=binary oflag=binary status=noxfer"
elif (platform=="RVL"):
    DD_CYGWIN = ""

isViewer = 0
isBoot = 0
noMeta = 0
isOS = 0
common = 1
newTicketId = 0
titleName = ""
list = ""
mFile = ""
cidList=""
cidxList=""
typeList=""
limits=""
dvd = 0
acr = 0
group = ES_DEFAULT_GID
genTicket = 1
debug = 0
genWad = 0
sysAccess = ""
isCompatBoot = 0
isCompatApp = 0
reserved1 = ""
reserved2 = ""
resourceManagers = ""
orderSpecified = 0
cidxMaskOpt = ""
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/%s/tmd" % (ROOT, HOST)
    TKT_TOOL = "%s/usr/bin/%s/ticket" % (ROOT, HOST)
    CONFIG_TOOL = "%s/usr/bin/linux/configHash.py" % (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
    CONFIG_TOOL = "\"%s/X86/bin/configHash.py\"" % ROOT
    ttype = ES_TITLE_TYPE_NG_TITLE
    ctype = ES_CONTENT_TYPE_NG_EXE
sub = 0 #do not issue subscription ticket
ctypes=""
bootVersion = 0
PADDING = 64
cblobFile = "c.blob"
crlFile = "crl.sys"
tmpFile = "tmp.met"
titleVersion = 0
bootIdx = 0
titleId = 0
ticketInputFile = ""
tmdExtraArgs = ""
accessTitleId = 0
accessTitleMask = 0
optionalCnt = ""

def printVersion():
    print "%s Version %d.%d" % (sys.argv[0], VERSION_MAJOR, VERSION_MINOR)
    sys.exit(1)

def printUsage():
  if platform=="RVL" or platform=="PPC":
    print "usage:  %s -n <name> [-l <elf1>,<elf2>,...] [-m <metaFile>] [-v] [-b] [-O] [-B] [-A] [-s] [-T <sharedFlag1>,<sharedFlag2>,...] [-a <cidx1,cidx2...>] [-P <d|b>] [-C <channel>] [-I <titleVersion>[-q <boot2Version>] [-o <osVersion>] [-D <deviceCertFile>] [-R] [-V] [-S] [-i] [-t] [-L <limitCode1,limitCode2,... limit1,limit2...>] [-p] [-w <wad input files>] [-d] [-z] [-G <titleId>] [-y <ticketFile>] [-E <accessTitleId>] [-e <accessTitleMask>]" % 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 "        -M: skip generating meta content 0"
    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 "        -s: stream title"
    print "        -f: data title"
    print "        -T <sharedFlag1,sharedFlag2,...>: "
    print "            shared flag for each of the content files, default 0"
    print "            1: shared; 0: unshared"
    print "        -W <optionalFlag1,optionalFlag2,...>: "
    print "            optional flag for each of the content files, default 0"
    print "            1: optional; 0: necessary"
    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 "        -I <titleVersion>: title version (default 0)"
    print "        -q <boot2Version>: boot2 version (default 0)"
    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 "        -i: issue individual 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 "        -N <32 byte binary file for Nintendo reserved data in TMD>"
    print "        -c <30 byte binary file for additional reserved data in TMD>"
    print "        -g <groupId>: groupID for the title"
    print "        -p: publish title only, do not ticket"
    print "        -d: keep output files for debugging"
    print "        -z: print version and exit"
    print "        -G <titleId>: titleId"
    print "        -y <ticketFile>: use ticket to generate wad"
    print "        -E <accessTitleId>: 32 bit titleId for streaming "
    print "                            media's access control "
    print "        -e <accessTitleMask>: 32 bit titleId  mask for streaming "
    print "                              media's access control "
    print "        -r <resource managers>: allow IPC access to the specified resource managers"
    print "        -X: make a wad file with specified order (does not change meta and boot)"
    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)

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

if (sys.argv[1] == "-z"):
    printVersion()

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

#get argments
try:
    opts, args = getopt.getopt(sys.argv[1:], "vzbMOitL:n:l:m:P:C:I:q:o:D:ST:a:g:pw:dRVBAsN:c:G:y:E:e:r:W:Xf")
except getopt.GetoptError:
    printUsage()
for o, v in opts:
    if o=="-v":
        isViewer = 1
    elif o=="-z":
        printVersion()
    elif o=="-b":
        isBoot = 1
    elif o=="-t":
        newTicketId = 1
    elif o=="-L":
        limits = v
    elif o=="-i":
        common=0
    elif o=="-n":
        titleName = v
    elif o=="-P":
        pki = v
    elif o=="-C":
        channel = long(v, 0)
    elif o=="-O":
        isOS = 1
    elif o=="-I":
        titleVersion = long(v, 0)
    elif o=="-q":
        bootVersion = long(v, 0)
    elif o=="-o":
        osVersion = long(v, 0)
    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=="-M":
        noMeta = 1
    elif o=="-g":
        group = int(v)
    elif o=="-p":
        genTicket = 0
    elif o=="-w":
        genWad = 1
        genTicket = 0
        wfiles = v
    elif o=="-d":
        debug = 1
    elif o=="-V":
        dvd = 2
    elif o=="-R":
        acr = 1
    elif o=="-B":
        isCompatBoot = 1
    elif o=="-A":
        isCompatApp = 1
    elif o=="-s":
        ttype |= ES_TITLE_TYPE_STREAM
    elif o=="-N":
        reserved1 = " -N " + v
    elif o=="-c":
        reserved2 = " -B " + v
    elif o=="-r":
        resourceManagers = v
        reserved2 = " -B rm.hash"
    elif o=="-G":
        titleId = long(v, 0)
    elif o=="-y":
        genTicket = 0
        ticketInputFile = v
    elif o=="-E":
        accessTitleId = long(v, 0)
    elif o=="-e":
        accessTitleMask = long(v, 0)
    elif o=="-W":
    	optionalCnt = v;
    elif o=="-X":
    	orderSpecified = 1
    elif o=="-f":
        ttype |= ES_TITLE_TYPE_DATA
        orderSpecified = 1 #But not exactly same as -X since -l cannot include meta file

if titleName=="":
    print "need to specify title name"
    printUsage()
if len(titleName) >= 32:
    print "titleName must be less than 32 characters"
    sys.exit(-1)

buildstamp = strftime("%y%m%d%H%M", gmtime())
user = os.getenv("USERNAME")
if user is None:
    user = ""
computer = os.getenv("COMPUTERNAME")
if computer is None:
    computer = ""
username = user + "@" + computer
username = username[:15]

if ttype & ES_TITLE_TYPE_DATA:
    channel = 0x00010005
    if titleId != 0:
        if (titleId >> 32) != channel:
            print "data title must use 0x%08x as titleIdHi" % channel
            sys.exit(-1)
        gameCode1 = (titleId >> 24) & 0xFF
        if gameCode1 < 0x61 or gameCode1 > 0x7A:
            print "data title must use lowercase 'a-z' ASCII value as first game code character"
            sys.exit(-1)
    if list == "":
        print "please provide -l argument"
        sys.exit(-1)

if isViewer==1:
    ticketId = ES_VIEWER_TICKET_ID
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL
    titleId = (channel<<32) | ES_VIEWER_TITLE_ID
    osVersion = (channel<<32) | osVersion
    group = 1
    common = 1
elif isBoot==1:
    ticketId = ES_BOOT_TICKET_ID
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL
        osVersion = bootVersion
        titleVersion = bootVersion
    titleId = (channel<<32) | ES_BOOT_TITLE_ID
    group = 1
    common = 1
elif isOS==1:
    if platform=="RVL" or platform=="PPC":
        channel = ES_SYS_CHANNEL_RVL
        ticketId = osVersion
    titleId = (channel<<32) | osVersion
    osVersion = bootVersion
    group = 1
    common = 1
else:
    if isCompatBoot==1:
        titleId = (ES_SYS_CHANNEL_RVL<<32) | ES_TITLE_ID_COMPATBOOT1
        osVersion = bootVersion
        group = 1
        common = 1
    elif isCompatApp==1:
        titleId = (ES_SYS_CHANNEL_RVL<<32) | ES_TITLE_ID_COMPATAPP
        osVersion = bootVersion
        group = 1
        common = 1
    else:
        if titleId==0:
            if ttype & ES_TITLE_TYPE_DATA:
                titleId = (channel<<32) | (0x61 << 24) | (abs(hash(titleName+"titleId")) & 0x00ffffff)
            else:
                titleId = (channel<<32) | abs(hash(titleName+"titleId"))
        osVersion = (ES_SYS_CHANNEL_RVL<<32) | osVersion
    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"))

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

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":
        certFileName = "%s/X86/bin/pki_data/cert_%spki.sys" % (ROOT, pki)
        certFile = string.replace(certFileName, "\\", "/")
    else:
        certFileName = "%s/usr/etc/pki_data/cert_%spki.sys" % (ROOT, pki)
        certFile = string.replace(certFileName, "\\", "/")
    if ticketInputFile=="":
        ticketFile = "%x.tik" % ticketId
    else:
        ticketFile = ticketInputFile
        fd = open(ticketFile, "rb")
        # Use the same titleId as the ticket
        fd.seek(476)
        titleId = long("%d" % struct.unpack('>Q', fd.read(8)))
        # Use the same titleKey as the ticket
        fd.seek(447)
        tk = fd.read(16)
        fd.close()
        fd = open("%x.titleKey" % titleId, "wb")
        fd.write(tk)
        fd.close()
        tmdExtraArgs += "-K %x.titleKey " % titleId
    tmdFile = "%x.tmd" % titleId
    metaFile = "%08x.met" % metaCid

print "ticketId = 0x%016x" % ticketId
print "titleId  = 0x%016x" % titleId
#print "metaCid = %08x.met" % metaCid

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

if list!="" or mFile!="":
    fd = open(metaFile, "wb")
    if isBoot!=1 and noMeta!=1:
        # write WADMeta structure (wad.h)
        fd.write(titleName + "." + buildstamp)
        pad = "\0" * (44 - (len(titleName) + 1 + len(buildstamp)))
        fd.write(pad)
        fd.write(struct.pack('B', VERSION_MAJOR))
        fd.write(struct.pack('B', VERSION_MINOR))
        fd.write(struct.pack('>H', 0x0000))
        fd.write(username)
        pad = "\0" * (16 - len(username))
        fd.write(pad)                           # pad to 32B
        fd.close()
        if mFile!="":
            os.system("cp %s %s" % (metaFile, tmpFile))
            os.system("cat %s %s > %s" % (tmpFile, mFile, metaFile))
            os.system("rm -rf %s" % tmpFile)
    else:
        fd.close()

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

    if isBoot==1 or noMeta==1:
        # sys app, so do not add meta to content index 0
        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(",")))
    else:
        if ttype & ES_TITLE_TYPE_DATA:
            contents.insert(0,metaFile)
        elif orderSpecified == 0:
            # move boot to the end
            if list != "":
                contents_tmp=contents[1:]
                contents_tmp.append(contents[0])
            else:
                contents_tmp=[]
            # add meta to the front
            contents_tmp.insert(0,metaFile)
            contents=contents_tmp

        bootIdx = len(contents)-1
        if ttype & ES_TITLE_TYPE_DATA:
            bootIdx = 511
        #print "contents=%s" % contents
        #print "bootIdx = %d" % bootIdx

        cidList = ("0x%08x" % metaCid)
        if list!="":
            cidList += "," + ",".join(map(lambda x: "0x%08x" % abs(hash(titleName+x)), contents[1:]))
        #print "cidList=%s" % cidList
        cidxList = ",".join(map(lambda x: "%d" % (x), range(len(contents))))
        #print "cidxList=%s" % cidxList

        if typeList=="":
            typeList = ",".join(map(lambda x: "0", range(len(contents)-1)))

        if optionalCnt=="":
            if ttype & ES_TITLE_TYPE_DATA:
        	    optionalCnt = ",".join(map(lambda x: "1", range(len(contents)-1)))
            else:
        	    optionalCnt = ",".join(map(lambda x: "0", range(len(contents)-1)))

        # rotate typeList since boot is at the end
        if orderSpecified == 0:
            #print "Original typeList=%s" % typeList
            #print "Original optionalCnt=%s" % optionalCnt
            typeList_tmp=typeList.split(",")
            typeList=typeList_tmp[1:]
            typeList.append(typeList_tmp[0])
            optionalCnt_tmp=optionalCnt.split(",")
            optionalCnt=optionalCnt_tmp[1:]
            optionalCnt.append(optionalCnt_tmp[0])
            #print "typeList=%s" % typeList
            #print "optionalCnt=%s" % optionalCnt
            ctypes = "0x1," + ",".join(map(lambda x,y: "0x%x"%((int(x)<<15)|(int(y)<<14)|ctype), typeList, optionalCnt))
            #print "ctypes=%s" % ctypes
        else:
            #print "typeList=%s" % typeList
            typeList=typeList.split(",")
            optionalCnt=optionalCnt.split(",")
            ctypes = "0x1," + ",".join(map(lambda x,y: "0x%x"%((int(x)<<15)|(int(y)<<14)|ctype), typeList, optionalCnt))
            #print "ctypes=%s" % ctypes
        list=string.join(contents,",")

    rights = (dvd | acr)
    if resourceManagers != "":
        os.system("%s -c %s -o rm.hash" % (CONFIG_TOOL, resourceManagers))
    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 %d -r 0x%08x -g 0x%x -P %s -m 0x%x %s %s" % (TMD_TOOL, ttype, ctypes, osVersion, stid, titleId, list, cidList, cidxList, bootIdx, rights, group, pki, titleVersion, reserved1, reserved2)
    else:
        tmd = "%s -O -C 0x%x -t \"%s\" -o 0x%x -T 0x%x -n \"%s\" -c \"%s\" -i \"%s\" -b %d -r 0x%08x -g 0x%x -P %s -m 0x%x %s %s %s" % (TMD_TOOL, ttype, ctypes, osVersion, titleId, list, cidList, cidxList, bootIdx, rights, group, pki, titleVersion, reserved1, reserved2, tmdExtraArgs)
    print tmd
    os.system(tmd)

#run "ticket"
if genTicket==1:
    if isBoot!=1:
        sysAccess = "-a 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15"

    if limits!="":
        lc = limits.split(" ")[0]
        l = limits.split(" ")[1]
        limits = "-L %s -l %s" % (lc, l)
    if ttype & ES_TITLE_TYPE_DATA:
        cidxMaskOpt = "-C 0 -c 512 "
    if common==1:
        ticket = "%s -O -t 0x%x -T 0x%x -K %x.titleKey -P %s %s %s -E 0x%x -e 0x%x %s" % (TKT_TOOL, ticketId, stid, stid, pki, limits, sysAccess, accessTitleId, accessTitleMask, cidxMaskOpt)
    elif common==0:
        ticket = "%s -O -t 0x%x -T 0x%x -K %x.titleKey -i -D %s -P %s %s %s -E 0x%0x -e 0x%x %s" % (TKT_TOOL, ticketId, stid, stid, devCertFile, pki, limits, sysAccess, accessTitleId, accessTitleMask, cidxMaskOpt)
    print ticket
    os.system(ticket)

#output .wad file
#### publish title and ticket
os.system("cat /dev/null > %s" % crlFile)
if (list!="" and ((genTicket==1) or ticketInputFile!="")) or (genWad==1):
    # write padded content list blob
    if (genWad==1):
        cblobList = contentFiles
    else:
        cblobList = map(lambda x: "%s.app" % x[2:], cidList.split(","))
    for f in cblobList:
        st = os.stat(f)
        tf = "%s.pad" % f
        cmd = "dd if=%s of=%s bs=%d conv=sync %s" % (f, tf, PADDING, DD_CYGWIN)
        os.system(cmd)
    cmd = "cat %s > %s" % (" ".join(map(lambda x: "%s.pad" % x[0:], cblobList)), cblobFile)
    os.system(cmd)
    st = os.stat(cblobFile)

    # write wad header file
    sizeFile = open("wad.head", "wb")
    contentOffset = WAD_HEADER_SIZE
    sizeFile.write(struct.pack('>i', contentOffset)) #hard code ESWadHeader size
    if (isBoot):
        sizeFile.write(struct.pack('c', 'i'))        #wadType
        sizeFile.write(struct.pack('c', 'b'))        #wadType
    else:
        sizeFile.write(struct.pack('c', 'I'))        #wadType
        sizeFile.write(struct.pack('c', 's'))        #wadType
    sizeFile.write(struct.pack('>H', 0))             #wadVersion

    padList = [certFile, crlFile, ticketFile, tmdFile, cblobFile, metaFile]
    for f in padList:
        st = os.stat(f)
        sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
        tf = "\"%s\".pad" % f
        cmd = "dd if=%s of=%s bs=%d conv=sync %s" % (f, tf, PADDING, DD_CYGWIN)
        os.system(cmd)
    sizeFile.close()
    cmd = "dd if=wad.head of=wad.head.pad bs=%d conv=sync %s" % (PADDING, DD_CYGWIN)
    os.system(cmd)

    catCmd = "cat wad.head.pad %s > %s.wad" % (" ".join(map(lambda x: "\"%s\".pad" % x[0:], padList)), titleName)

#### publish title only
elif list!="" and genTicket==0 and ticketInputFile=="":
    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) or (ticketInputFile!=""):
    print "ticketInputFile %s" % ticketInputFile
    print "certFile %s" % certFile
    print "ticketFile %s" % ticketFile
    sizeFile = open("wad.head", "wb")
    sizeFile.write(struct.pack('>i', WAD_HEADER_SIZE)) #hard code ESWadHeader size
    sizeFile.write(struct.pack('c', 'I'))              #wadType
    sizeFile.write(struct.pack('c', 's'))              #wadType
    sizeFile.write(struct.pack('>H', 0))               #wadVersion

    padList = [certFile]
    for f in padList:
        st = os.stat(f)
        sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
        tf = "\"%s\".pad" % f
        cmd = "dd if=\"%s\" of=%s bs=%d conv=sync %s" % (f, tf, PADDING, DD_CYGWIN)
        os.system(cmd)

    sizeFile.write(struct.pack('>i', 0)) #crl size

    padList = [ticketFile]
    for f in padList:
        st = os.stat(f)
        sizeFile.write(struct.pack('>i', st[stat.ST_SIZE]))
        tf = "\"%s\".pad" % f
        cmd = "dd if=\"%s\" of=%s bs=%d conv=sync %s" % (f, tf, PADDING, DD_CYGWIN)
        os.system(cmd)

    sizeFile.write(struct.pack('>i', 0)) #tmd size
    sizeFile.write(struct.pack('>i', 0)) #content size
    sizeFile.write(struct.pack('>i', 0)) #meta size
    sizeFile.close()
    cmd = "dd if=wad.head of=wad.head.pad bs=%d conv=sync %s" % (PADDING, DD_CYGWIN)
    os.system(cmd)

    padList = [certFile, ticketFile]
    catCmd = "cat wad.head.pad %s > %s.wad" % (" ".join(map(lambda x: "\"%s\".pad" % x[0:], padList)), titleName)

print catCmd
os.system(catCmd)

#clean up
os.system("rm -rf wad.head pad.tmp %s.pad *.pad rm.hash %s %s" % (certFile, cblobFile, crlFile))
if debug==0:
    os.system("rm -f %s %s %s %x.titleKey" % (ticketFile, tmdFile, metaFile, stid))
    if list!="":
        os.system("rm -f %s" % (" ".join(map(lambda x: "%s.app" % x[2:], cidList.split(",")))))

