/* iosim 
 *  shell command interpreter 
 * 
 * :set expandtab
 * :set shiftwidth=4
 * :set tabstop=4
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <getopt.h>
#include "req_cmd.h"
#include "utils.h"
#include "cmd.h"
#include "ipc.h"

#define OPTARG               "i:vV?hH"
int socket_status = 0;       /* local socket status */
int cur_socket = -1;         /* current open socket */

void 
dvUsage()
{
    printf( "Usage: shell [-vV] [-hH] [-i id]\n"
            "\tc socket_name             - close which socket: cpu0, cpu1 or gba  \n"
            "\to socket_name             - open which socket: cpu0, cpu1 or gba \n"
            "\tp                         - Ping current socket \n"
            "\tP                         - Ping current socket + COMMIT \n"
            "\tq                         - Quit shell \n"
            "\tQ                         - Quit shell and simulator \n"
            "\ts socket_name             - Switch to which socket \n"
            "\tt                         - Return simulator time in ns \n"
            "\tT                         - t cmd + commit \n"
            "\tta type n                 - Simulator time advance \n"
            "\t        type: gba, cpu, ns  \n"
            "\t                     gba  - gba pos edge clk \n"
            "\t                     core - core clk pos edge clk \n"
            "\t                     cpu0 - cpu0 neg edge clk \n"
            "\t                     cpu1 - cpu1 neg edge clk \n"
            "\t                     ns   - ns clk \n" 
            "\tTA                        - ta cmd + commit \n"
          );
}

int 
main(int argc, char **argv)
{
    char *line=NULL, *expansion = NULL;
    int result, c, i;
    char *p;
    int loop = 1, verbose = 0, sel;
    unsigned int num;
    char history_file[256];
    FILE *fp=NULL;
    long long cur_time;

    while ((c = getopt(argc, argv, OPTARG)) != EOF) {
        switch (c) {
        case 'i':
            DV_SetCmdId(dvGetCmdArgNum(optarg));
            break;                
        case 'v':
        case 'V': 
            verbose = 1;
            break;
        case 'h':
        case 'H':
        case '?':
            dvUsage();
            exit(1);
            break;
        }  /* end of switch */
    }

    if (getenv("HOME")) {
        strcpy(history_file, getenv("HOME"));
    } else {
        history_file[0] = '.';
        history_file[0] = '\0';
    }
    strcat(history_file, "/.sc_ipc_history");
    read_history(history_file);

    for (;loop;) {
        if (line) {
            free(line);
        }
        if ((line = readline("> ")) == NULL) {
            break;
        }

        result = history_expand(line, &expansion);
        if (expansion) {
            free(line);
            line = expansion;
        }

        if (result < 0 || result == 2) {
            printf("%s \n", line);
            continue;
        }

        if ((p = strrchr(line, '\n'))) *p = '\0';
        for (p = line; *p && isspace(*p); ++p);
        if (*p) {
            add_history(p);
        }
        if (fp) {
            fprintf(fp, "%s\n", p);
        }

        switch (p[0]) {
        case 'c':
            num = dvGetCmdArgConnect(p+1);
            DV_CloseSocket(num, verbose);
            if ((num == cur_socket) && (cur_socket > 0)) {
                printf("WARNING: %s closed, call s to switch to another socket\n",
                        DV_IpcSocketName(num));
                cur_socket = -1;
            }
            break;
        case 'o':   /* Socket connect */
            num = dvGetCmdArgConnect(p+1);
            if (!DV_IpcWaitTillConnected(num, verbose)) 
                cur_socket = num;
            break;
        case 'p':
        case 'P':
            DV_Ping(cur_socket, (p[0]=='p') ? 0 : 1);     
            break;
        case 'Q':   /* Quit shell + simulator */
        case 'q':   /* Quit shell */
            loop = 0;
            if (p[0] == 'Q') {
                if (cur_socket>=0) {
                        DV_IpcQuit(cur_socket, verbose);
                } else {
                    printf("WARNING: no active socket, simulator not terminated\n");
                }
            }
            sleep(3);  /* eliminate race for close */
            for (i=0; i<IPC_SOCK_NUM; i++) {
                if (DV_IpcIsConnected(i)) {
                    if (p[0] == 'q')
                        DV_CloseSocket(i, verbose);
                    else DV_IpcClose(i, verbose);
                }
            }
            break;     
        case 's':
            num = dvGetCmdArgConnect(p+1);
            if (DV_IpcIsConnected(num)) { 
                cur_socket = num;
            } else {
                printf("WARNING: %s not open(use o cmd) yet \n",
                        DV_IpcSocketName(num)); 
            }
            break;
        case 't':
        case 'T':
            if ((p[1] == ' ') || (p[1] == '\0')) {
                if (cur_socket >= 0) {
                    cur_time = DV_RtlTime(cur_socket, verbose);
                    printf("Simulator time: %lld ns \n", cur_time);
                } else {
                    printf("INFO: use s or o cmd open socket\n");
                }
            } else { 
                if ((p[1] == 'a') || (p[1] == 'A')) {
                    dvCmdTimeAdv(cur_socket, p+2, (p[0]=='t')?0:1, verbose);  
                }
            }
            break;
        case 'h':
        case 'H':
        case '?':
        default:
            dvUsage();
            break;
        } /* end of switch */

        
        if (loop) {
            if (DV_IsAllSocketCommit()) {
                sel = 0;
                while (sel == 0) { 
                    sel = DV_SocketSelect();
                }

                for (i=0; i<IPC_SOCK_NUM; i++) {
                    if (sel & (1<<i)) {
                        dvHandleRecvData(i, verbose);
                        DV_IpcSetCommit(i, 0);
                        if (cur_socket != i) {
                            printf("INFO: %s to Active \n", DV_IpcSocketName(i));
                            cur_socket = i;            
                        }
                        break;
                    }
                }  /* end of for */   
            }  
        } /* end of if loop */   
    }

    if (line) {
        free(line);
    }
    write_history(history_file);
    history_truncate_file(history_file, 100);    
    return 0;
}

