#ident "$Id: imageCompose.c,v 1.5 2007/04/05 21:35:47 craig Exp $"
/*
 *               Copyright (C) 2006, 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.
 *
 */

/*
 * Program to generate a disk image from an unencrypted section,
 * a table of contents, and one or more partitions.
 * 
 * Example command line:
 * ./imageCompose.exe -u test_nand_partition.unencrypt
 *                    -t test_nand_partition.TOC
 *                    -p test_nand_partition.up.0
 *                    -p test_nand_partition.game.1
 *                    -p nand_part.dev_part
 *
 * This code is derived from Nintendo's makeRVTR program.
 */


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

/*
 * Need to define this, or else on Cygwin the ticket and tmd
 * structures are laid out differently than on Linux
 */
#define BROADWAY_REV
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <netinet/in.h>         // For htonl()
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include "types.h"
#include "disk_format.h"
#include "estypes.h"
#include "tool_common.h"
#include "disk_common.h"
#include "masterimage.h"        /* From Nintendo */
#include "master_common.h"      /* From Nintendo */
#include "DF_structs.h"

// Declare strdup rathern than define __USE_SVID or __USE_BSD on
// Linux FC 3 systems.
extern char *strdup(const char *s);

#define PATH_LEN                1024
#define COMMAND_LEN             2048
#define IMAGE_SIZE              4700012544
#define MAX_NUM_PARTITIONS      16

#if !defined(__CYGWIN__)
static struct option longOptions[] = {
    {"help",            0, 0, 'h'},     /* Print usage */
    {"keep",            0, 0, 'k'},     /* keep intermediate files */
    {"part",            1, 0, 'p'},     /* partition name */
    {"toc",             1, 0, 't'},     /* table of contents name */
    {"unencrypt",       1, 0, 'u'},     /* unencrypted part of file */
    {"verbose",         0, 0, 'v'},     /* Print status output when running */
    {0, 0, 0, 0}
};
#endif

static char* options = "hkp:t:u:v";
char            *ProgName;
bool            Verbose = false;

typedef struct optionVals {
    char *outputName;
    char *unencryptedName;
    char *tocName;
    char **partNames;
    int  numPartNames;
    bool keepFiles;
} optionVals_t;

bool produceImage(const optionVals_t* const optionVals);
void usage();
/* ------------------------------------------------------------------------ */

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

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

    // Default values
    optionVals->outputName              = NULL;
    optionVals->unencryptedName         = NULL;
    optionVals->tocName                 = NULL;
    optionVals->partNames               = NULL;
    optionVals->numPartNames            = 0;
    optionVals->keepFiles               = false;

    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 'k':
            optionVals->keepFiles = true;
            break;

        case 'o':
            optionVals->outputName = optarg;
            break;

        case 'p':
            partNamesArray[numPartitions++] = optarg;
            break;

        case 't':
            optionVals->tocName = optarg;
            break;

        case 'u':
            optionVals->unencryptedName = optarg;
            break;

        case 'v':
            Verbose = true;
            break;

        default:
            fprintf (stderr, "Unknown option '%c' - exit\n", ch);
            usage();
            exit(1);
        }
    }
    if (optionVals->tocName == NULL) {
        fprintf(stderr, "%s: Must use the -t flag to set the TOC name\n",
                ProgName);
        usage();
        exit(1);
    }
    if (optionVals->unencryptedName == NULL) {
        fprintf(stderr, "%s: Must use the -t flag to set the TOC name\n",
                ProgName);
        usage();
        exit(1);
    }
    if (numPartitions == 0) {
        fprintf(stderr,
                "%s: Must use the -p flag to specify at least one partition\n",
                ProgName);
        usage();
        exit(1);
    }
    optionVals->numPartNames = numPartitions;
    optionVals->partNames = (char **) malloc(sizeof (char *) * numPartitions);
    if (optionVals->partNames == NULL) {
        fprintf (stderr, "%s: Allocating partition name array failed\n",
                 ProgName);
        exit(1);
    }
    for (int i = 0; i < numPartitions; i++) {
        size_t          stringLen;

        stringLen = strlen(partNamesArray[i]);
        optionVals->partNames[i] = (char *) malloc(stringLen + 1);
        if (optionVals->partNames[i] == NULL) {
            fprintf (stderr,
                     "%s: Allocation of %u bytes for partition name failed\n",
                     ProgName, stringLen);
            exit(1);
        }
        strcpy(optionVals->partNames[i], partNamesArray[i]);
    }

    if (optionVals->outputName == NULL) {
        char    *suffixPtr, tempName[PATH_LEN];

        suffixPtr = rindex(optionVals->partNames[0], (int) '.');
        if (suffixPtr == NULL) {
            sprintf(tempName, "%s.rvm", optionVals->partNames[0]);
        }
        else {
            strcpy(tempName, optionVals->partNames[0]);
            suffixPtr = rindex(tempName, (int) '.');
            if (suffixPtr == NULL) {
                fprintf(stderr, "(%s) Can't find '.' in copy of partition name\n",
                ProgName);
                exit(1);
            }
            *suffixPtr = '\0';
            strcat(tempName, ".rvm");
        }
        optionVals->outputName = strdup(tempName);
        if (optionVals->outputName == NULL) {
            fprintf(stderr, "%s: Duplicating output name failed - exit\n",
                    ProgName);
            exit(1);
        }
    }
} // processOptions
/* ------------------------------------------------------------------------ */

void
usage()
{
    fprintf (stderr, "Usage: %s [options] -u [unencrypted section] -t [TOC section] -p partition1 [-p partition2]...\n",
                     ProgName);
    fprintf (stderr, 
        " Options:\n"
        " -h, --help            - print usage message\n"
        " -k, --keep            - keep intermediate files (for debugging)\n"
        " -t, --toc             - table of contents portion of image\n"
        " -u, --unencrypt       - unencrypted portion of image\n"
        " -v, --verbose         - print out messages as image is created\n"
        "\n");

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

int
main(int argc, char *argv[])
{
    optionVals_t        optionVals;
    int                 exitVal = 1;

    ProgName = argv[0];

    if (Verbose) {
        printf ("%s version 0.01 %s\n", ProgName, __DATE__);
    }
    processOptions(argc, argv, &optionVals);

    if (produceImage(&optionVals) == false) {
        goto end;
    }
    exitVal = 0;

end:
    exit(exitVal);
}

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

bool
produceImage(const optionVals_t* const optionVals)
{
    FILE                *outImage = NULL;
    bool                returnVal = false;
    off_t               tocStart, partitionInfoOffset;
    DF_GameTOC          gameToc;
    DF_PartitionInfo    *newPartInfo;
    size_t              partitionInfoSize;

    if ((outImage = fopen(optionVals->outputName, "w+b")) == NULL) {
        fprintf(stderr, "%s: Can't open file %s for writing\n",
                ProgName, optionVals->outputName);
    }
    if (copyBinFileToOutFile(outImage, optionVals->unencryptedName) == false) {
        goto end;
    }
    tocStart = ftello(outImage);
    if (copyBinFileToOutFile(outImage, optionVals->tocName) == false) {
        goto end;
    }
    if (fseeko(outImage, tocStart, SEEK_SET) != 0) {
        fprintf(stderr, "%s: Can't seek in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }

    if (fread(&gameToc, sizeof(DF_GameTOC), 1, outImage) != 1) {
        fprintf(stderr, "%s: Can't read game TOC in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    /* Update number of game partitions */
    gameToc.numGamePartitions = htonl(optionVals->numPartNames);
    if (fseeko(outImage, tocStart, SEEK_SET) != 0) {
        fprintf(stderr, "%s: Can't seek in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    if (fwrite(&gameToc, sizeof(DF_GameTOC), 1, outImage) != 1) {
        fprintf(stderr, "%s: Can't write game TOC in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }

    partitionInfoOffset =  (htonl(gameToc.partitionInfos) << 2)
                           + RVM_HEADER_LENGTH;
    partitionInfoSize = sizeof(DF_PartitionInfo) * optionVals->numPartNames;
    newPartInfo = malloc(partitionInfoSize);
    if (newPartInfo == NULL) {
        fprintf(stderr, "%s: Allocating %d partition infos failed \n",
                ProgName, optionVals->numPartNames);
        goto end;
    }
    /*
     * Because we could have more partition infos than before, and its
     * possible the additonal partition infos will make the TOC
     * portion bigger than before, write out the new array.  It
     * will contain garbage values that will be overwritten
     */
    if (fseeko(outImage, partitionInfoOffset, SEEK_SET) != 0) {
        fprintf(stderr, "%s: Can't seek in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    if (fwrite(newPartInfo, partitionInfoSize, 1, outImage) != 1) {
        fprintf(stderr, "%s: Can't write new partition info in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    for (int i = 0; i < optionVals->numPartNames; i++) {
        off_t curOffset, partitionStart;

        curOffset = ftello(outImage) - RVM_HEADER_LENGTH;
        partitionStart = alignAddress(curOffset, PARTITION_ALIGN);
        newPartInfo[i].gamePartition = DISK_ADDR(partitionStart);
        if (UNDO_DISK_ADDR(newPartInfo[i].gamePartition) != partitionStart) {
            fprintf(stderr, "%s: (UNDO_)DISK_ADDR macros are broken (%llx != %llx)!\n",
                    ProgName, UNDO_DISK_ADDR(newPartInfo[i].gamePartition),
                    partitionStart);
            goto end;
        }
        if (i == 0) {
            newPartInfo[i].type = htonl(UPDATE_PARTITION);
        }
        else if (i == 1) {
            newPartInfo[i].type = htonl(BOOT_GAME_PARTITION);
        }
        else {
            newPartInfo[i].type = htonl(GAME_PARTITION);
        }
        if (fseeko(outImage, partitionStart + RVM_HEADER_LENGTH,
                   SEEK_SET) != 0) {
            fprintf(stderr, "%s: Can't seek in file %s\n",
                    ProgName, optionVals->outputName);
            goto end;
        }
        if (copyBinFileToOutFile(outImage, optionVals->partNames[i]) == false) {
            goto end;
        }
    }

    /* Now write the updated partition info array */
    if (fseeko(outImage, partitionInfoOffset, SEEK_SET) != 0) {
        fprintf(stderr, "%s: Can't seek in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    if (fwrite(newPartInfo, partitionInfoSize, 1, outImage) != 1) {
        fprintf(stderr, "%s: Can't write new partition info in file %s\n",
                ProgName, optionVals->outputName);
        goto end;
    }
    returnVal = true;
end:
    if (outImage != NULL) {
        if (fclose(outImage) != 0) {
            fprintf(stderr, "%s: Closing file %s failed [%s]\n",
                    ProgName, optionVals->outputName, strerror(errno));
            returnVal = false;
        }
    }
    return(returnVal);
} // produceImage

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