/*
 *  Test main file  
 *  Parse input parameter and 
 *  call function test_proc(void *)
 *  :set expandtab
 *  :set tabstop=4
 */

#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include "dv.h"

/* Test Proc function 
   return 0 if succeed, 
   return errcode if error occurs.
 */
extern int testProc(void *);

static void 
usage(char *name)
{
    printf("Usage: %s [options]\n", name);
    printf("    -q : Quit simulator after it is done\n");
    printf("    -c <cpu0|cpu1|gba> : run through which channel\n");
    printf("    -C <kernel0 | kernel1 | ... | kernel7> : CFG mode\n");
    printf("    -N not initialize Sdram(default initialize) \n");
    printf("    -s <seed> : random seed\n");
    printf("    -n <name> : name of test\n");
    printf("    -a <string> : additional info passed to testProc\n");
    printf("    -t <timeout> : test timeout. Default is 1000000(1ms)\n");
    printf("    -L <filename> : regression log file\n");
    printf("    -l <filename> : test log file (default is stderr, stdout) \n");
    printf("    -r <filename> : bin(instruction file to load to boot rom \n");
    printf("    -D <filename> : bin(instruction file to load to DA \n");
    printf("    -S <filename> : bin(instruction file to load to SDRAM \n");
    printf("    -p : not check clk/reset/rom-flip. \n");
    printf("         By default, clk/reset/rom-flip will be checked\n");
    printf("    -E <e|w|n>: test exit level\n");
    printf("        e -- Exit if internal error occurs\n"); 
    printf("        w -- Exit if internal error or warning occurs\n"); 
    printf("        n -- only print out msg if internal err/warn occurs\n"); 
    printf("    -w <1|2> : Use SOCK_SYNC to Sync\n");
    printf("        This options should put before -c \n"); 
    printf("        1 -- Busy wait for SockSync msg \n");
    printf("        2 -- Send SockSync, sleep 1 and continue \n");
	printf("    -z: skip usual test setup\n");
    printf("    -h : print this help\n");
    printf("    -? : help\n");
}

static void 
createTestArgument(
    DVCmdStruct *pcmd, 
    char *name, 
    char *add)
{
    int c;
    char *tmp, *str;
    char *buf;

    optind = 0;
    if ((add == NULL) || (name == NULL)) {
    	pcmd->argc = 1;
    	pcmd->argv = (char **) malloc(sizeof(char *));
	if (pcmd->argv) pcmd->argv[0] = name;
        return;
    }

    c = 1;
    tmp = add;
    while ((tmp[0] == ' ') || (tmp[0] == '\t'))
        tmp++;  /* remove blank */
    str = tmp;

    while (tmp[0] != 0) {
        c++;
        while ((tmp[0] != ' ') && (tmp[0] !='\t') && (tmp[0] != 0))
            tmp++;
        
        while ((tmp[0] == ' ') || (tmp[0] == '\t'))
            tmp++;
    }

    buf = malloc(strlen(add) + 1);
    pcmd->argc = c;
    pcmd->argv = (char **) malloc(c * sizeof(char *));
    if ((buf == NULL) || (pcmd->argv == NULL)) {
        printf("ERROR: cannot alloc memory for %d arg %s \n", c, add);
        return;
    }
    strcpy(buf, str);

    tmp = buf;
    c = 0;
    pcmd->argv[0] = name;
    while (tmp[0] != 0) {
        c++;
        pcmd->argv[c] = tmp;
        while ((tmp[0] != ' ') && (tmp[0] !='\t') && (tmp[0] != 0))
            tmp++;
        
        while ((tmp[0] == ' ') || (tmp[0] == '\t'))
            *tmp++ = '\0';
    }

    return;
}

static int
parseCfg(char *str)
{
    int cfg = CFG_KEEP;

    if (strcmp(str, "kernel0") == 0) {
        cfg = CFG_KERNEL_0; 
    } else if (strcmp(str, "kernel1") == 0) {
        cfg = CFG_KERNEL_1;
    } else if (strcmp(str, "kernel2") == 0) {
        cfg = CFG_KERNEL_2;
    } else if (strcmp(str, "kernel3") == 0) {
        cfg = CFG_KERNEL_3;
    } else if (strcmp(str, "kernel4") == 0) {
        cfg = CFG_KERNEL_4;
    } else if (strcmp(str, "kernel5") == 0) {
        cfg = CFG_KERNEL_5;
    } else if (strcmp(str, "kernel6") == 0) {
        cfg = CFG_KERNEL_6;
    } else if (strcmp(str, "kernel7") == 0) {
        cfg = CFG_KERNEL_7;
    } else if (strcmp(str, "kernel") == 0) {
        cfg = CFG_KERNEL;
    }

    return cfg;
}

int 
main(int argc, char **argv)
{
    DVCmdStruct cmd;
    int ret, seed=time(NULL), runTest=1, cfg=CFG_KEEP, cpuModel=1;
    char *name, *cmdArg, buf[256];
    char *boot=NULL, *da=NULL, *sdram=NULL;
    int openSocks = 0, wait=0;
    int quit=0, c, verbose=0, clkCheck=1, initSdram=1;
    int test_to = 20000000;  /* 20 ms timeout */
	int optZ = 0;
    unsigned int exLevel = DV_EXIT_WARNING;

    name = argv[0];
    cmd.argv = NULL;
    cmd.flog = cmd.ferr = NULL;
    cmdArg = NULL;
    regressionLog = stdout;
    
    /* Parse arguments here */
    while ((c = getopt(argc, argv, "c:s:n:a:L:l:pqh?vE:C:t:r:D:S:w:Nz")) != EOF) {    
        switch (c) {
        case 's':
            seed =  atoi(optarg);
            break;
        case 'C':
            cfg = parseCfg(optarg);
            break;
        case 'c':
            if (strstr(optarg, "cpu0")) {
                openSocks |= 1<<IPC_SOCK_CPU0;
                DV_Cpu0Start(verbose);
                if (wait) {
                    if (wait == 1) {
                        DV_WaitSockSync(IPC_SOCK_CPU0);
                        DV_CpuSimContinue();
                        DV_WaitSockSync(IPC_SOCK_CPU0);
                    } else {
                        DV_SockSync(IPC_SOCK_CPU0, IPC_SOCK_CPU1, 0);
                        sleep(2);  
                    }
                }
                DV_GetArmBusModel(IPC_SOCK_CPU0, &cpuModel);
                if (cpuModel) { /* Behavior model */
                    DV_ResetStatus(IPC_SOCK_CPU0, &ret);
                    if ((ret & IPC_SC_CPU0_RST_MASK) != 0) {
                        printf("WARNING: CPU0 is not out of reset \n");
                        DV_CpuWaitReset();
                    }
                }
            }

            if (strstr(optarg, "cpu1")) {
                openSocks |= 1<<IPC_SOCK_CPU1;
                DV_Cpu1Start(verbose);
                if (wait) {
                    if (wait == 1) {
                        DV_WaitSockSync(IPC_SOCK_CPU1);
                        DV_CpuSimContinue();
                        DV_WaitSockSync(IPC_SOCK_CPU1);
                    } else {
                        DV_SockSync(IPC_SOCK_CPU1, IPC_SOCK_CPU0, 0);
                        sleep(2);  
                    }
                }
                DV_GetArmBusModel(IPC_SOCK_CPU1, &cpuModel);
                if (cpuModel) { /* Behavior model */
                    DV_ResetStatus(IPC_SOCK_CPU1, &ret);
                    if ((ret & IPC_SC_CPU1_RST_MASK) != 0) {
                        printf("ERROR: CPU1 is not out of reset \n");
                        runTest = 0;
                    }
                }   
            }
            if (strstr(optarg, "gba")) {
                openSocks |= 1<<IPC_SOCK_GBA;
                DV_GbaStart(verbose);
                DV_GetArmBusModel(IPC_SOCK_GBA, &cpuModel);
                if (cpuModel) { /* Behavior model */
                    DV_WaitGbaReady();
                }
            }
            break;
        case 'a': 
            cmdArg = optarg;
            break;
        case 'l':
            sprintf(buf, "%s.out", optarg);
            if ( (cmd.flog = fopen(buf, "a+b")) == NULL) {
                printf("ERROR: cannot open %s \n", buf);
                runTest = 0;
            } 
            sprintf(buf, "%s.err", optarg) ;
            if ( (cmd.ferr = fopen(buf, "a+b")) == NULL) {
                printf("ERROR: cannot open %s \n", buf);
                runTest = 0;
            } 
            break;         
        case 't':
            test_to = atoi(optarg);
            break;
        case 'L':
            if ((regressionLog = fopen(optarg, "a+b")) == NULL) {
                printf("ERROR: cannot open %s \n", optarg);
                runTest = 0; 
            }
            break;
        case 'p':
            clkCheck = 0;
            break;
        case 'E':
            if (optarg[0] == 'n' || optarg[0] == 'N')  {
                exLevel = DV_EXIT_NORMAL;
            } else if (optarg[0] == 'e' || optarg[0] == 'E') {
                exLevel = DV_EXIT_ERROR;
            } else exLevel = DV_EXIT_WARNING;
            break; 
        case 'n':
            name = optarg;
            break;
        case 'r':
            boot = optarg;
            break;
        case 'D':
            da = optarg;
            break;
        case 'S':
            sdram = optarg;
            break;
        case 'q':
            quit = !quit;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'w':
            wait = atoi(optarg);
            if (wait > 2 || wait < 0) wait = 0;
            break;
        case 'N':
            initSdram = 0;
            break;
		case 'z':
			optZ = 1;
			break;
        case 'h':
        case '?':        
        default:
            usage(name);
            runTest = 0;
        }
    }

    if (cmd.flog == NULL) cmd.flog = stdout;
    if (cmd.ferr == NULL) cmd.ferr = stdout;
    if (regressionLog == NULL)  regressionLog = stdout;
    exitLevel = exLevel;
    quitSimulator = quit;

    srand(seed);

    ret = 0;
    if (runTest) {
        if (openSocks == 0) {
            DV_RegressionLog(regressionLog, cmd.flog, "ERROR %s cannot Start 1", name);
            usage(name);
            return -1;
        }

        numWarnings = numErrors = 0;
        DV_RegressionLog(regressionLog, cmd.flog, "%s Start(seed=%d)", name, seed);
        createTestArgument(&cmd, name, cmdArg);

		// do not run below option filtering for -z;

		if( !optZ) {
        	if (clkCheck && cpuModel) DV_TurnOnAllClocks();

        	if (boot != NULL) DV_BdWriteFile(boot, BOOT_START);
        	if (!cpuModel) { /* Wait cpu out of reset */
            	DV_ResetStatus(IPC_SOCK_CPU0, &ret);
            	if ((ret & IPC_SC_CPU0_RST_MASK) != 0) {
                	printf("WARNING: CPU0 is not out of reset \n");
                	DV_CpuWaitReset();
            	}
        	}

        	if (da != NULL) DV_BdWriteFile(da, DA_START);
        	if (sdram != NULL) DV_BdWriteFile(sdram, MEM0_START);
        	if ((cfg != CFG_KEEP) && cpuModel) 
            	DV_SetTestCfg(cfg);
        	if (initSdram && cpuModel)  DV_InitSdram(0);

        	DV_SetTestTimeout(test_to);
		}

        /* Run Test */ 

        ret = testProc(&cmd);
        if (ret) {
            DV_RegressionLog(regressionLog, cmd.flog, "ERROR: %s Failed errCode=%d", name, ret);
        } else {
            if (numErrors) {
                DV_RegressionLog(regressionLog, cmd.flog,
                        "ERROR: %s got %d internal errors & %d warnings!", 
                        name, numErrors, numWarnings);
            } else if (numWarnings) {
                DV_RegressionLog(regressionLog, cmd.flog,
                        "%s Succeeded but %d warnings!", name, numWarnings);
            } else {
                DV_RegressionLog(regressionLog, cmd.flog, "%s Succeeded!", name);
            }
        }
    } else {
        DV_RegressionLog(regressionLog, cmd.flog, "ERROR %s cannot Start", name);
    }     
    
    DV_CloseAllSocket(quit, verbose);
    if (regressionLog != stdout) fclose(regressionLog);
    if (cmd.ferr != stdout) fclose(cmd.ferr);
    if (cmd.flog != stdout) fclose(cmd.flog);

    if (cmd.argv != NULL) {
        if (cmd.argc > 1) free(cmd.argv[1]);   /* free cmd buffer */
        free(cmd.argv);
    } 

    return ret;
}
