/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished proprietary information of BroadOn Communications Corp.,
 *  and are protected by federal copyright law. They may not be disclosed
 *  to third parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */


#include <types.h>
#include <ioslibc.h>
#include <iostypes.h>
#include <ios.h>
#include <fs.h>
#include <estypes.h>
#include <es_int.h>
#include <es.h>

#define IMPORT_DATA_BUF_SIZE 17*1024
#define ID_STR_LEN 8

static ESWadHeader* head = NULL;
static ESTicket* ticketBuf = NULL;
static ESTitleMeta* tmdBuf  = NULL;
static u8* metaBuf  = NULL;
static u8* certBuf = NULL;
static u8* dataBuf = NULL;

static void
tmpAlloc(int certSize, int tmdSize)
{
    ticketBuf = (ESTicket*)IOS_Alloc(0, sizeof(ESTicket));
    tmdBuf = (ESTitleMeta*)IOS_Alloc(0, tmdSize);
    certBuf = (u8*)IOS_AllocShaAlign(0, certSize);
    dataBuf = (u8*)IOS_AllocShaAlign(0, IMPORT_DATA_BUF_SIZE);
}

static void
tmpFree()
{
    IOS_Free(0, ticketBuf);
    IOS_Free(0, tmdBuf);
    IOS_Free(0, certBuf);
    IOS_Free(0, dataBuf);
    ticketBuf = NULL;
    tmdBuf = NULL;
    certBuf = NULL;
    dataBuf = NULL;
}

static s32
__importTicket(FILE *fd)
{
    ESError rv = ES_ERR_OK;
    int len=0;

    len = fread((u8*)certBuf, 1, ntohl(head->certSize), fd);
    if (len!=ntohl(head->certSize)) {
        printf("read cert failed: %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    len = fread((u8*)ticketBuf, 1, sizeof(ESTicket), fd);
    if (len!=sizeof(ESTicket)) {
        printf("read ticket failed: %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }
    
    rv = ES_ImportTicket(ticketBuf, certBuf, ntohl(head->certSize), NULL, 0,
                         ES_TRANSFER_SERVER);
    if (rv != ES_ERR_OK) {
        printf("Unable to import ticket: %d\n", rv);
        goto out;
    }
    printf ("import ticket successful\n");

out:
    return rv;
}

//TODO: this should be part of the ES_Import APIs
static s32
__importMeta(const u8* metaBuf)
{
    ESError rv = ES_ERR_OK;
    char tmPath[] = "/tmp/title.met";
    char dir1[] = "/meta/00000000";
    char dir2[] = "/meta/00000000/00000000";
    char mPath[] = ES_META_FILE;
    ESTitleId hTitleId;
    u32 num;

#define esTitleL(t) ((u32)(((u64)t)&0xffffffff))
#define esTitleH(t) ((u32)((((u64)t)>>32)&0xffffffff))

    hTitleId = ntohll(tmdBuf->head.titleId);
    snprintf(dir1, sizeof(dir1), "/meta/%08x", esTitleH(hTitleId));
    snprintf(dir2, sizeof(dir2), "/meta/%08x/%08x", 
             esTitleH(hTitleId), esTitleL(hTitleId));
    snprintf(mPath, sizeof(mPath), "/meta/%08x/%08x/title.met", 
             esTitleH(hTitleId), esTitleL(hTitleId));

    rv = ISFS_ReadDir(dir1, NULL, &num);
    if (rv==ISFS_ERROR_NOEXISTS) {
        rv = ISFS_CreateDir(dir1, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
        if (rv!=ISFS_ERROR_OK) {
            printf("create %s failed %d\n", dir1, rv);
            goto out;
        }
    }
    rv = ISFS_ReadDir(dir2, NULL, &num);
    if (rv==ISFS_ERROR_NOEXISTS) {
        rv = ISFS_CreateDir(dir2, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
        if (rv!=ISFS_ERROR_OK) {
            printf("create %s failed %d\n", dir2, rv);
            goto out;
        }
    }
    rv = ISFS_CreateFile(tmPath, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (rv!=ISFS_ERROR_OK) {
        printf("create file %s failed %d\n", tmPath, rv);
        goto out;
    }
    s32 mfd = ISFS_Open(tmPath, ISFS_WRITE_ACCESS); 
    if (mfd<0) {
        printf("open file %s failed %d\n", tmPath, mfd);
        rv = ES_ERR_FILE_OPEN_FAILED;
        goto out;
    }
    rv = ISFS_Write(mfd, metaBuf, ntohl(head->metaSize));
    if (rv!=ntohl(head->metaSize)) {
        printf("write file %s failed %d\n", tmPath, mfd);
        rv = ES_ERR_FILE_WRITE_FAILED;
        goto out;
    }
    rv = ISFS_Close(mfd);
    mfd = -1;
    if (rv!=ISFS_ERROR_OK) {
        printf("close file %s failed %d\n", tmPath, rv);
        goto out;
    }

    rv = ISFS_Rename(tmPath, mPath);
    if (rv!=ISFS_ERROR_OK) {
        printf("dir rename failed %d\n", rv);
        goto out;
    }

    printf("successfully written meta file %s\n", mPath);

out:
    if (mfd!=-1) ISFS_Close(mfd);
    return rv;
}

static s32
__doImportTitle(FILE * fd)
{
    ESError rv = ES_ERR_OK;
    u16 numContents;
    int len;
    int pad;

    len = fread((u8*)tmdBuf, 1, ntohl(head->tmdSize), fd);
    if (len!=ntohl(head->tmdSize)) {
        printf("read tmd failed: %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    metaBuf = (u8*)IOS_Alloc(0, ntohl(head->metaSize));
    len = fread((u8*)metaBuf, 1, ntohl(head->metaSize), fd);
    if (len!=ntohl(head->metaSize)) {
        printf("read meta file failed: %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    pad = ntohl(head->contentOffset) - sizeof(ESWadHeader) - 
          ntohl(head->certSize) - ntohl(head->ticketSize) - 
          ntohl(head->tmdSize) - ntohl(head->metaSize);
    if (pad<0 || fread(dataBuf, 1, pad, fd)!=pad) {
        printf("failed to read padding in wad file %d\n", pad);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    rv = ES_ImportTitleInit(tmdBuf, ntohl(head->tmdSize), certBuf, ntohl(head->certSize), 0, 0, ES_TRANSFER_SERVER, 1);
    if (rv != ES_ERR_OK) {
        printf("Unable to import title init: %d\n", rv);
        goto out;
    }
    printf("imported TMD\n");

    numContents = ntohs(tmdBuf->head.numContents);
    int i;
    for (i = 0; i < numContents; ++i) {

        s32 clen, read;
        s32 cfd = ES_ImportContentBegin(ntohll(tmdBuf->head.titleId), ntohl(tmdBuf->contents[i].cid));
        if (cfd < 0) {
            printf("Unable to import content %d: %d\n", i, cfd);
            rv = cfd;
            goto out;
        }

        clen = (ntohll(tmdBuf->contents[i].size)+15) & ~15;
        printf("Importing %d bytes for content %d\n", clen, i);
        while (clen) {
            u32 bytes = clen > IMPORT_DATA_BUF_SIZE ? IMPORT_DATA_BUF_SIZE : clen;
            read = fread(dataBuf, 1, bytes, fd);
            if (read!=bytes) {
                printf("content file read failed %d\n", read);
                rv = ES_ERR_FILE_READ_FAILED;
                goto out;
            }
            if ((rv = ES_ImportContentData(cfd, dataBuf, bytes)) < 0) {
                printf("Error import content data: %d [%d]\n", rv, clen);
                goto out;
            }
            clen -= bytes;
        }

        if ((rv = ES_ImportContentEnd(cfd)) != ES_ERR_OK) {
            printf("Unable to end content import: %d\n", rv);
            goto out;
        }
    }

    if ((rv = ES_ImportTitleDone()) != ES_ERR_OK) {
        printf("Unable to finish import: %d\n", rv);
        goto out;
    }
    printf("Successfully imported title\n");

    rv = __importMeta(metaBuf);
    if (rv!=ES_ERR_OK) {
        printf("import meta file failed\n", rv);
        goto out;
    }

out:
    if (metaBuf) IOS_Free(0, metaBuf);
    return rv;
}

static s32
__importTitle(FILE *fd)
{
    ESError rv = ES_ERR_OK;
    int len;

    len = fread((u8*)certBuf, 1, ntohl(head->certSize), fd);
    if (len!=ntohl(head->certSize)) {
        printf("read cert failed: %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    rv = __doImportTitle(fd); 

out:
    return rv;
}

static s32
__importAll(FILE *fd)
{
    ESError rv = ES_ERR_OK;

    rv = __importTicket(fd);
    if (rv!=ES_ERR_OK) {
        goto out;
    }

    rv = __doImportTitle(fd); 

out:
    return rv;

}

s32
import(const char* name) 
{
    ESError rv = ES_ERR_OK;
    FILE *fd = NULL;
    s32 len = 0;

    head = (ESWadHeader*)IOS_Alloc(0, sizeof(ESWadHeader));
    fd = fopen(name, "rb"); 
    if (fd==NULL) {
        printf("unable to open file %s\n", name); 
        rv = ES_ERR_FILE_OPEN_FAILED;
        goto out;
    }

    len = fread((u8*)head, 1, sizeof(ESWadHeader), fd); 
    if (len!=sizeof(ESWadHeader)) {
        printf("unable to get header from .wad file %d\n", len);
        rv = ES_ERR_FILE_READ_FAILED;
        goto out;
    }

    if (head->certSize==0 || head->metaSize==0 || 
        (head->ticketSize==0 && head->tmdSize==0) || 
        (head->ticketSize!=0 && ntohl(head->ticketSize)!=sizeof(ESTicket))) {
        printf("invalid .wad file header certSize=%d ticketSize=%d tmdSize=%d metaSize=%d\n", ntohl(head->certSize), ntohl(head->ticketSize), ntohl(head->tmdSize), ntohl(head->metaSize)); 
        rv = ES_ERR_INVALID;
        goto out;
    }
    tmpAlloc(ntohl(head->certSize), ntohl(head->tmdSize));

    if (ntohl(head->ticketSize)==0) {
        rv = __importTitle(fd);
    } else if (ntohl(head->tmdSize)==0) {
        rv = __importTicket(fd);
    } else {
        rv = __importAll(fd);
    }

    printf("import returned %d\n", rv);

out:
    tmpFree();
    IOS_Free(0, head);
    head = NULL;
    if (fd>=0) fclose(fd);
    return rv;
}

