/*
 *               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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include <netinet/in.h>

#include "esl.h"
#include "es_int.h"
#include "utils.h"
#include "rsautil.h"

#if !defined(__CYGWIN__)
static struct option __longOptions[] = {
    {"IN", 1, 0, 'I'},         /* input cert file to be verified */
    {"OUT", 1, 0, 'O'},        /* output cert and RSA file */
    {"type", 1, 0, 't'},       /* type of cert to be created */
    {"name", 1, 0, 'n'},       /* id/name of the cert */
    {"issuerCert", 1, 0, 'c'}, /* issuer cert file */
    {"issuerRsa", 1, 0, 'r'},  /* issuer rsa data file */
    {"inputRsa", 1, 0, 'i'},   /* input rsa data file */
    {"exponent", 1, 0, 'e'},   /* RSA exponent */
    {"devPvt", 1, 0, 'd'},     /* device's ECC private key file */
    {"print", 0, 0, 'p'},      /* verify cert and dump fields of cert file */
    {"size", 0, 0, 's'},       /* print out sizes of various certs */
    {"help", 0, 0, 'h'},       /* print usage */
    {0, 0, 0, 0}
};
#endif

static char* __options = "I:c:dph";

static char* __inCertFile = NULL;
static const char* __issuerCertFile = NULL;
static char __type = 0;
static char __pre[2];
static int __dump = 0;
static int __print = 0;
static void* __cert = NULL;

typedef struct {
    char dev_info[16];
    u8 dev_cert[sizeof(IOSCEccEccCert)];
    u8 sig_dum[sizeof(IOSCEccSig)];
    u8 sig_pad[4];
    u8 app_cert[sizeof(IOSCEccEccCert)];
    u8 padding[16];
} record;

static record recordData;

static void
usage(const char* progName)
{
    fprintf(stderr, "usage: %s\n", progName);
    fprintf(stderr,
        " -I, --IN <file>         - input cert file to be verified.\n"
        " -c, --issuerCert <file> - issuer cert file.\n"
        " -p, --print             - verify cert & dump fields of cert file.\n"
        " -d, --dump              - dump device cert to binary file.\n"
        " -h, --help              - print this message.\n");
    exit(1);
} 


static void
processOptions(int argc, char* argv[])
{
    if (argc==1) 
        usage(argv[0]);

    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 'I':
                __inCertFile = optarg;
                break;
            case 'c':
                __issuerCertFile = optarg;
                break;
            case 'd':
                __dump = 1;
                break;
            case 'p':
                __print = 1;
                break;
            default:
                usage(argv[0]);
                break;
        }
    }

    if (__inCertFile==NULL) {
        fprintf(stderr, "provide input cert file using -I\n");
        usage(argv[0]);
    }

    switch (__type) {
        case 'r':
            sprintf(__pre, "%s", ES_ROOT_NAME);
            break;
        case 'a':
            sprintf(__pre, "%s", ES_CA_PREFIX);
            break;
        case 'x':
            sprintf(__pre, "%s", ES_XS_PREFIX);
            break;
        case 'p':
            sprintf(__pre, "%s", ES_CP_PREFIX);
            break;
        case 'm':
            sprintf(__pre, "%s", ES_MS_PREFIX);
            break;
        case 'd':
            sprintf(__pre, "%s", ES_NC_PREFIX);
            break;
        case 'D':
            sprintf(__pre, "%s", ES_NG_PREFIX);
            break;
    }
}


static void
dumpCert(char* args) 
{
    IOSCCertSigType st;
    IOSCCertPubKeyType pt=0;
    u8* ptr=NULL;
    int i, ret, count;
    struct stat statBuf;
    char *file=NULL;
    char dumpFile[30], serNoStr[15], devIdStr[15], bbIdStr[20];
    // long long bbId;
    int sigSize=0, keySize, size=0;
    FILE *fptr, *dfptr;

    /* get cert */
    if (__inCertFile) {
        stat(__inCertFile, &statBuf);
        file = __inCertFile;
    } else {
        fprintf(stderr, "specify input cert file using -I or create new cert file using -O\n");
        usage(args);
    }

    dfptr = NULL;
    fptr = fopen(file, "rb");
    if (fptr==NULL) {
        fprintf(stderr, "file open failed %s\n", file);
        exit(1);
    }

    count = 0;
    while (1) {

        count++;
        memset(&recordData, 0, sizeof(record));

        if ((ret = fread((u8 *)&recordData, sizeof(u8), sizeof(record), fptr))!=
            sizeof(record)) {
            if (!feof(fptr))
                fprintf(stderr, "file read failed %s, ret=%d\n", file, ret);
            exit(1);
        }

        __cert = (u8 *)recordData.dev_cert;

        memset(serNoStr,  0, sizeof(serNoStr));
        memset(devIdStr,  0, sizeof(devIdStr));
        memset(dumpFile, 0, sizeof(dumpFile));
        memcpy(serNoStr, recordData.dev_info, 9);

        if (__print) {
            printf("Device Id     = %s\n", 
                ((IOSCEccEccCert*)__cert)->head.name.deviceId);
            printf("Serial Number = %s\n", serNoStr);
        }
         
        if (__dump) {
            sprintf(dumpFile,  "%s_%s.bin", 
                ((IOSCEccEccCert*)__cert)->head.name.deviceId, serNoStr);
            dfptr = fopen(dumpFile, "wb");
            if (dfptr==NULL) {
                fprintf(stderr, "file open failed %s\n", dumpFile);
                exit(1);
            }
            if ((ret = fwrite((u8 *)__cert,sizeof(u8),sizeof(IOSCEccEccCert), 
                dfptr))!= sizeof(IOSCEccEccCert)) {
                fprintf(stderr, "file write failed %s, ret=%d\n",dumpFile,ret);
                exit(1);
            }
        } /* if */

        st = ntohl(*((u32*)__cert));
        switch (st) {
            case IOSC_SIG_RSA4096:
                pt = ntohl(((IOSCRsa4096RsaCert*)__cert)->head.pubKeyType);
                switch (pt) {
                    case IOSC_PUBKEY_RSA4096: 
                        sigSize = 0;
                        keySize = sizeof(CSLOSRsaPublicKey4096);
                        if (__print) {
                            utilDumpCert1(__cert, IOSCRootCert);
                            utilDumpCert2(__cert, IOSCRootCert);
                        }
                        size = sizeof(IOSCRootCert);
                        break;
                    case IOSC_PUBKEY_RSA2048:
                        sigSize = sizeof(CSLOSRsaSig4096);
                        keySize = sizeof(CSLOSRsaPublicKey2048);
                        if (__print) {
                            utilDumpCert1(__cert, IOSCRsa4096RsaCert);
                            utilDumpCert2(__cert, IOSCRsa4096RsaCert);
                        }
                        size = sizeof(IOSCRsa4096RsaCert);
                        break;
                    default:
                        break;
                }
                break;
            case IOSC_SIG_RSA2048:
                pt = ntohl(((IOSCRsa2048RsaCert*)__cert)->head.pubKeyType);
                switch (pt) {
                    case IOSC_PUBKEY_ECC: 
                        sigSize = sizeof(CSLOSRsaSig2048);
                        keySize = sizeof(CSLOSEccPublicKey);
                        if (__print) {
                            utilDumpCert1(__cert, IOSCRsa2048EccCert);
                        }
                        size = sizeof(IOSCRsa2048EccCert);
                        break;
                    case IOSC_PUBKEY_RSA2048:
                        sigSize = sizeof(CSLOSRsaSig2048);
                        keySize = sizeof(CSLOSRsaPublicKey2048);
                        if (__print) {
                            utilDumpCert1(__cert, IOSCRsa2048RsaCert);
                            utilDumpCert2(__cert, IOSCRsa2048RsaCert);
                        }
                        size = sizeof(IOSCRsa2048RsaCert);
                        break;
                    default:
                        break;
                }
                break;
            case IOSC_SIG_ECC:
                pt = ntohl(((IOSCEccEccCert*)__cert)->head.pubKeyType);
                switch (pt) {
                    case IOSC_PUBKEY_ECC: 
                        sigSize = sizeof(CSLOSEccSig);
                        keySize = sizeof(CSLOSEccPublicKey);
                        if (__print) {
                            utilDumpCert1(__cert, IOSCEccEccCert);
                        }
                        size = sizeof(IOSCEccEccCert);
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }

        /* 
         * Display format: devID (hex), devID (decimal), serial number, OK/BAD 
         */ 
        strncpy(devIdStr,(u8*)(((IOSCEccEccCert*)__cert)->head.name.deviceId+2),
                8);
        bbIdStr[0]= '0';
        bbIdStr[1]= 'x';
        bbIdStr[2]= '1';
        strncpy((u8 *)(bbIdStr+3), 
            (u8*)(((IOSCEccEccCert*)__cert)->head.name.deviceId+2),8);
        // bbId = atoll(bbIdStr);
        // bbId = 0x10416a7d5;

        s32 createdDate = (s32)(ntohl(((IOSCEccEccCert*)__cert)->head.date) - 
                          (20*365*24*60*60));
        printf("%s,%s,%s,%s,%u,%d,", bbIdStr, devIdStr, serNoStr, 
            ((IOSCEccEccCert*)__cert)->head.name.deviceId,
            (u32)(ntohl(((IOSCEccEccCert*)__cert)->head.date)),createdDate);

        if (__issuerCertFile!=NULL) {
            if ( utilVerify(__issuerCertFile, sigSize, __cert, size)!=ES_ERR_OK)
                // printf("cert verify failed\n");
                printf("BAD\n");
            else
                // printf("cert verify successful\n");
                printf("OK\n");
        }
        if (__dump) {
            fclose(dfptr);
        }
    } /* while */

    fclose(fptr);

}

int
main(int argc, char* argv[])
{
    processOptions(argc, argv);

    dumpCert(argv[0]);

    return 0;
}
