#ident "$Id: rvl0_image.c,v 1.3 2006/10/05 00:25:40 craig Exp $"
/*
 *               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.
 *
 */

/*
 *
 */


#ifdef __CYGWIN__
#undef __STRICT_ANSI__
#else
#define fseeko(file, where, whence)     fseeko64(file, where, whence)
#define ftello(file)                    ftello64(file)
#endif

#include <errno.h>
#include <getopt.h>
#include <netinet/in.h>         // For ntohl()
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>            // For index()
#include <sys/types.h>          // For off_t and stat
#include <sys/stat.h>           // For stat()
#include <unistd.h>

#include "types.h"
#include "disk_common.h"

#define FILE_NAME_MAX    256
#define PATH_LEN        1024
#define COMMAND_LEN     2048
#define PROGRAM_VERSION "0.01"

#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"help",            0, 0, 'h'},     /* Print usage */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {0, 0, 0, 0}
};
#endif

static char* options = "hv";
char            *ProgName;
bool            Verbose = false;

typedef struct optionVals {
    char        *inputName;
} optionVals_t;


static bool fileExists(const char* const fileName);
static bool composeImage(const optionVals_t* const optionVals,
                         const char* const dlfName,
                         const char* const rcfName);
static bool splitLine(char* const line, u64 *offset, char *name);
void        usage();

/* ------------------------------------------------------------------------ */

/*
 * Process the program arguments.
 * OUTPUT:
 *              Sets the titleKey
 */

void
processOptions(int argc, char* argv[], optionVals_t* const optionVals)
{
    ProgName = argv[0];

    // Default values
    optionVals->inputName               = NULL;


    while (1) {
#if defined(__CYGWIN__)
        int ch = getopt(argc, argv, options);
#else
        int ch = getopt_long_only(argc, argv, options, longOptions, 0);
#endif

        if (ch == -1)
            break;

        switch (ch) {

        case 'h':
            usage();
            exit(0);
            break;

        case 'v':
            Verbose = true;
            break;

        default:
            fprintf (stderr, "Unknown option '%c' - exit\n", ch);
            usage();
            exit(1);
        }
    }
    if (optind >= argc) {
        fprintf (stderr, "%s: Need input name\n", ProgName);
        usage();
        exit(1);
    }
    else {
        optionVals->inputName = argv[optind];
    }
} // processOptions
/* ------------------------------------------------------------------------ */

void
usage()
{
    fprintf (stderr, "%s version %s %s\n", ProgName,
             PROGRAM_VERSION, __DATE__);
    fprintf (stderr, "Usage: %s input_base_name\n", ProgName);
    fprintf (stderr,
        " Options:\n"
        " -h, --help            - print usage message\n"
        " -v, --verbose         - print out messages\n"
        "\n");

}
/* ------------------------------------------------------------------------ */

int
main(int argc, char *argv[])
{
    optionVals_t        optionVals;
    char                rcfName[FILE_NAME_MAX], dlfName[FILE_NAME_MAX];
    int                 exitValue = 1;

    ProgName = argv[0];

    processOptions(argc, argv, &optionVals);

    if (Verbose) {
        printf ("%s version %s %s\n", ProgName, PROGRAM_VERSION, __DATE__);
    }
    sprintf(rcfName, "%s.rcf", optionVals.inputName);
    sprintf(dlfName, "%s.dlf", optionVals.inputName);
    if (! fileExists(rcfName)) {
        fprintf(stderr, "%s: File %s does not exist\n", ProgName, rcfName);
        goto end;
    }
    if (! fileExists(dlfName)) {
        fprintf(stderr, "%s: File %s does not exist\n", ProgName, dlfName);
        goto end;
    }
    if (composeImage(&optionVals, dlfName, rcfName) == true) {
        exitValue = 0;
    }
    else {
        exitValue = -1;
    }

    exitValue = 0;
end:
    exit(exitValue);
}


/* ------------------------------------------------------------------------ */

#define IO_BUF_SIZE     (32 * 1024)
#define LINE_SIZE       1024

bool
composeImage(const optionVals_t* const optionVals,
             const char* const dlfName, const char* const rcfName)
{
    FILE        *dlfFile = NULL, *imageFile = NULL;
    char        imageName[FILE_NAME_MAX];
    char        fileName[FILE_NAME_MAX], dsfName[FILE_NAME_MAX];
    bool        returnVal = false;
    u8          lineBuf[LINE_SIZE];
    u64         offsetToFile, headerSize;

    // The .dlf is a text file -> don't specify 'b' to fopen
    if ((dlfFile = fopen(dlfName, "r")) == NULL) {
        goto end;
    }

    sprintf(imageName, "%s.gcm", optionVals->inputName);
    sprintf(dsfName,   "%s.dsf", optionVals->inputName);

    if ((imageFile = fopen(imageName, "wb")) == NULL) {
        goto end;
    }
    headerSize = 32 * 1024;
    if (copyBinFileToOutFile(imageFile, "rvm.header") == false) {
        goto end;
    }
    /*
    if (copyBinFileToOutFile(imageFile, rcfName) == false) {
        goto end;
    }
    */
    while (fgets(lineBuf, sizeof(lineBuf), dlfFile) != NULL) {

        if (strncmp(lineBuf, "0x", 2) != 0) {
            continue;
        }
        if (splitLine(lineBuf, &offsetToFile, fileName) == false) {
            continue;
        }
        if (strlen(fileName) == 0) {
            continue;
        }
        /*
        if (strcmp(fileName, dsfName) == 0) {
            continue;
        }
        */
        if (fseeko(imageFile, (off_t) offsetToFile + headerSize, SEEK_SET) == -1) {
            perror ("fseeko:");
            goto end;
        }
        if (Verbose) {
            printf ("%s: Writing file %s\n", ProgName,  fileName);
        }
        if (copyBinFileToOutFile(imageFile, fileName) == false) {
            goto end;
        }
    }
    returnVal = true;
end:
    if (dlfFile != NULL) {
        fclose(dlfFile);
    }
    if (imageFile != NULL) {
        fclose(imageFile);
    }
    return(returnVal);
} // composeImage
/* ------------------------------------------------------------------------ */

static bool
splitLine(char* const line, u64 *offset, char *name)
{
    char        *commaPtr, *inStringPtr, *outStringPtr;

    *offset = strtoull(line, NULL, 0);
    if ((commaPtr = index(line, ',')) == NULL) {
        return(false);
    }
    inStringPtr = commaPtr + 1;
    if (*inStringPtr != '"') {
        return(false);
    }
    inStringPtr++;

    outStringPtr = name;
    if (strncmp(inStringPtr, "C:", 2) == 0) {
        inStringPtr += 2;
        strcpy(name, "/cygdrive/c");
        outStringPtr += strlen(name);
    }
    while (*inStringPtr != '"') {
        if (*inStringPtr == '\\') {
            *outStringPtr = '/';
        }
        else {
            *outStringPtr = *inStringPtr;
        }
        outStringPtr++;
        inStringPtr++;
    }
    *outStringPtr = '\0';
    return(true);
}

/* ------------------------------------------------------------------------ */

static bool
fileExists(const char* const fileName)
{
    struct stat statBuf;

    if (stat(fileName, &statBuf) == -1) {
        return(false);
    }
    else {
        return(true);
    }
}
/* ------------------------------------------------------------------------ */
