/*
 *               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.
 *
 *  Description:
 *      This file implements an utility to configure the SC
 *
 */


#include <types.h>
#include <sc/sc.h>
#include <ioslibc.h>
#include <apputils.h>
#include <estypes.h>
#include <es_int.h>
#include <es.h>

#define STACK_SIZE                  (2*1024)
const u8        _initStack[STACK_SIZE];
const u32       _initStackSize = sizeof(_initStack);
const u32       _initPriority = 10;


/* Maximum command line size including NULL character */
#define LINE_SIZE               128

static s32
quit(char *args, char *d)
{
    printf("Quitting...\n");

    exit(0);
    return (0);
}

ESTicket ticketBuf __attribute__((aligned(16)));
ESTitleMeta tmdBuf __attribute__((aligned(16)));
u8 certBuf[3328] __attribute__((aligned(16)));
u8 dataBuf[16384] __attribute__((aligned(16)));

static s32
__readFile(char *name, void *buf, u32 bytes)
{
    s32 rv = 0;
    s32 len;
    FILE *fp = NULL;

    fp = fopen(name, "rb");
    if (fp == NULL) {
        printf("Failed to open '%s'\n", name);
        rv = -1;
        goto out;
    }

    len = flen(fp);
    if (len > bytes) {
        printf("Buffer not big enough: %d > %d\n", len, bytes);
        rv = -1;
        goto out;
    }
    fread(buf, len, 1, fp);
    rv = len;
    printf("Read %d bytes from '%s'\n", len, name);

out:
    if (fp) fclose(fp);
    return rv;
}

static s32
importTicket(char *args, char *d)
{
    char *opt, *cert, *ticket;
    s32 certSize, ticketSize;
    s32 rv;
    
    if (getNextToken(&opt, &args) == 0) {
        goto out;
    }
    if (getNextToken(&cert, &args) == 0) {
        goto out;
    }
    if (getNextToken(&ticket, &args) == 0) {
        goto out;
    }

    if (((certSize = __readFile(cert, &certBuf, sizeof(certBuf))) < 0) ||
        ((ticketSize = __readFile(ticket, &ticketBuf, sizeof(ticketBuf))) < 0)) {
        goto out;
    }
    rv = ES_ImportTicket(&ticketBuf, &certBuf, certSize, NULL, 0,
                         ES_TRANSFER_SERVER);
    if (rv != ES_ERR_OK) {
        printf("Unable to import ticket: %d\n", rv);
        goto out;
    }

out:
    return 0;
}

static s32
importTitle(char *args, char *d)
{
    char *cert, *tmd;
    s32 certSize, tmdSize;
    u32 numContents;
    s32 rv;

    if (getNextToken(&cert, &args) == 0) {
        goto out;
    }
    if (getNextToken(&tmd, &args) == 0) {
        goto out;
    }
    if (((certSize = __readFile(cert, &certBuf, sizeof(certBuf))) < 0) ||
        ((tmdSize = __readFile(tmd, &tmdBuf, sizeof(tmdBuf))) < 0)) {
        goto out;
    }
    rv = ES_ImportTitleInit(&tmdBuf, tmdSize, &certBuf, certSize, 0, 0, ES_TRANSFER_SERVER);
    if (rv != ES_ERR_OK) {
        printf("Unable to import title init: %d\n", rv);
        goto out;
    }
    numContents = ntohl(tmdBuf.head.numContents);
    int i;
    for (i = 0; i < numContents; ++i) {
        char *contentName;
        FILE *fp;
        s32 len;
        s32 fd = ES_ImportContentBegin(ntohl(tmdBuf.head.titleId), ntohl(tmdBuf.contents[i].cid));
        if (fd < 0) {
            printf("Unable to import content %d: %d\n", i, fd);
            goto out;
        }
        if (getNextToken(&contentName, &args) == 0) {
            goto out;
        }
        fp = fopen(contentName, "rb");
        if (fp == NULL) {
            printf("Failed to open '%s'\n", contentName);
            goto out;
        }

        len = flen(fp);
        printf("Importing %d bytes from '%s'\n", len, contentName);
        while (len) {
            u32 bytes = len > sizeof(dataBuf) ? sizeof(dataBuf) : len;
            fread(dataBuf, bytes, 1, fp);
            if ((rv = ES_ImportContentData(fd, dataBuf, bytes)) < 0) {
                printf("Error import content data: %d [%d]\n", rv, len);
                goto out;
            }
            len -= bytes;
        }
        fclose(fp);
        if ((rv = ES_ImportContentEnd(fd)) != 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");

out:
    return 0;
}

/* Command blocks */
static Command commands[] = {
    {"importTicket", importTicket,
        "importTicket cert ticket   - Import ticket", 0},
    {"importTitle", importTitle,
        "importTitle cert tmd <contents>  - Import title", 0},
#if 0
    {"cd", cd,
        "cd dirname             - Change to a directory", 0},
    {"ls", ls,
        "ls                     - List the names of files and directories", 0},
    {"cp", cp,
        "cp src_file dst_file   - Copy a file", 0},
    {"get", get,
        "get src_file dst_file  - Get a file from the flash", 0},
    {"put", put,
        "put src_file dst_file  - Put a file onto the flash", 0},
    {"dump", dump,
        "dump fname             - Dump first 1KB of the file", 0},
    {"mkdir", mkdir,
        "mkdir dirname          - Create a new directory", 0},
    {"rm", rm,
        "rm name                - Remove a file or directory", 0},
    {"stat", stat,
        "stat name              - Get file stats", 0},
    {"format", format,
        "format                 - Re-format the flash", 0},
    {"writeboot", writeboot,
        "writeboot b1 b2 b3     - Write boot1, boot2, and boot3", 0},
    {"writeboot1", writeboot1,
        "writeboot1 boot1.aes   - Write boot1", 0},
    {"writeboot2", writeboot2,
        "writeboot2 boot2.aes   - Write boot2", 0},
    {"writeboot3", writeboot3,
        "writeboot3 boot3.elf   - Write boot3", 0},
#endif
    {"source",source,
        "source <file>          - Execute commands from file", commands},
    {"help", help,
        "help                   - Print this message", commands},
    {"quit", quit,
        "quit                   - Quit SC Monitor", 0},
    {0}
};


/*
 *  Function: main
 *
 *  Description:
 *      Entry point for CPU 0
 *
 *  Inputs:
 *      None
 *
 *  Ouputs:
 *      None
 *
 *  Return values:
 *      0 - Successful completion
 *      < 0 - Error values for regression tests
 *
 */
s32
main(void)
{
    char        line[LINE_SIZE];

    printf("ES Monitor\n");
    printf("built: " BUILD_TIME "\n\n");

    ES_InitLib();

    while (1) {
        printf("[ESMon] Enter command: ");
        gets(line);
        if (parseCommand(line, commands) < 0) {
            help("", (void *)commands);
        }
    }

    return 0;
}
