/*
 *              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 "utils.h"
#include "cmd.h"
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
#define STRCMP  strncasecmp

#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif

int
Usage()
{
    printf("Usage: ncshell [-b] [-i ip_address] [-p port_number] [-s script(batch mode)] \n");
    printf(" NC usb shell program\n");
    printf("\t  -b                  enable boot operation \n");
    printf("\t  -i ip_address       specify ncproxy ip address \n");
    printf("\t  -p port_number      specify ncproxy port number \n");
    printf("\t  -s script           run given script file\n");
    printf(" NC shell command:\n");
    printf("\th                     - help\n"
           "\tcd [new dir]          - change current directory\n"
           "\tdiag [aud|flash|rtc|gba] - run given diagnostics\n"
           "\tdate [MM/DD/YY HH:MM:SS] - get or set rtc \n"
           "\tformat                - format file system\n"
           "\tid                    - check programed id\n"
           "\timport pc_wad_file    - import a published app from pc to nc\n"
           "\tls                    - list file or directory\n"
           "\tpwd                   - get current directory\n"
           "\tmkdir dir             - create directory\n"
           "\tmv old new            - rename file (cp + rm) or dir\n"
           "\tnvt [0-7]             - Test nvram bit 0 - 7 \n"
           "\tnvrt                  - Read back nvram test area \n"
           "\tcp old new            - cp file \n"
           "\tping                  - handshake\n"
           "\tput pc_file [nc_file] - upload pc file to nc\n"
           "\tget nc_file [pc_file] - download nc_file to pc\n"
           "\trm [file/dir]         - remove file or directory\n"
           "\trb which_boot file    - download given boot and write to file\n"
           "\ts filename            - run given cmd script\n"
           "\tusage <flags>         - display kernel resource usage\n"
           "\tver                   - display build time\n"
           /*"\tlaunch elf_file       - launch elf file on NC\n" */ 
           /*"\twb which_boot file    - upload PC file to NC boot\n"*/
           "\tq                     - quit\n");

    return 0;
}

#define CMD_SIZE  256
static const char *default_ip = "127.0.0.1";
int
main(int argc, char **argv)
{
    char *p;
    char *server, *ret;
    int  port=20025, fd, c, boot=0; 
	FILE *f=NULL;
#ifdef USE_READLINE
    char *expansion = NULL, *cmdLine=NULL;
    int result;
    char history_file[256];
#else 
    char cmdLine[CMD_SIZE];
#endif

    struct timeval tm;
    fd_set rfd;

	server = (char *) default_ip;
	while ((c = getopt(argc, argv, "bp:i:s:hH?")) != EOF) {
		switch (c) {
		case 'b':
			boot = 1;
			break;
		case 'p':
			port=atoi(optarg);
			printf("NC shell port number changed to %d \n", port);
			break;
		case 'i':
			server = optarg;
			printf("NC shell proxy server ip change to %s \n", server);
			break;
		case 's':
			f = fopen(optarg, "rb");
			if (f == NULL) {
				printf("Cannot open given command file\n");
				return -1;
			} else printf("Run command script %s \n", optarg);
			break;
		case 'h':
		case 'H':
		case '?':
			Usage();
			break;
		default:
			printf("Unsupport cmd option = %c \n", c);
			break;
		}
	}

	printf("NC Shell built at %s\n", BUILD_TIME);
    fd  = shellInit(server, port);
    if (fd < 0) return -1;

    FD_ZERO(&rfd);
    FD_SET(fd, &rfd);
    tm.tv_sec = 0;
    tm.tv_usec = 20000;
    if (select(fd+1, &rfd, NULL, NULL, &tm) <= 0) 
        shellPing(fd, "ping N");

#ifdef USE_READLINE
    if (getenv("HOME")) {
        strcpy(history_file, getenv("HOME"));
    } else {
        history_file[0] = '.';
        history_file[1] = 0;
    }
    strcat(history_file, "/.nc_history");
    read_history(history_file);
#endif

    while (1) {

#ifdef USE_READLINE
        if (cmdLine) {
            free(cmdLine);
            cmdLine = NULL;
        } 
#endif 

        if (f == NULL) {
#ifdef USE_READLINE
            if ((cmdLine = readline("> ")) == NULL) {
                printf("Error: readline\n");
                goto out;
            } 
            expansion = NULL;
            result = history_expand(cmdLine, &expansion);
            if (expansion) {
                free(cmdLine);
                cmdLine = expansion;
            }

            if (result < 0 || result == 2) {
                printf("%s \n", cmdLine);
                continue;
            }
#else
            printf("> "); 
            fflush(stdout);
            if (!fgets(cmdLine, CMD_SIZE, stdin)) 
                break;
#endif
        } else {
#ifdef USE_READLINE
            cmdLine = (char *) malloc(CMD_SIZE);
            if (cmdLine == NULL) {
                printf("Error: cannot alloc command buffer\n");
                goto out;
            }
#endif
            ret = fgets(cmdLine, CMD_SIZE, f);
            if (ret == NULL) {
                fclose(f);
                f = NULL;
                continue;
            }
        }

        p = shellSkipBlank(cmdLine);
        shellNullTerminateCmd(cmdLine);
        
        if (strlen(p) == 0) 
            continue;

#ifdef USE_READLINE
        add_history(p);
#endif

        if (STRCMP(p, "cd", 2) == 0) {
            shellCd(fd, p);
        } else if (STRCMP(p, "cp", 2) == 0) {
            shellCp(fd, p);
        } else if (STRCMP(p, "diag", 4) == 0) {
            shellDiag(fd, p);
        } else if (STRCMP(p, "date", 4) == 0) {
            shellDate(fd, p);
        } else if (STRCMP(p, "format", 6) == 0) {
            shellFormat(fd, p);
        } else if (STRCMP(p, "usage", 5) == 0) {
            shellUsage(fd, p);
        } else if (STRCMP(p, "get", 3) == 0) {
            shellGet(fd, p);
        } else if (STRCMP(p, "launch", 6) == 0) {
            shellLaunch(fd, p);
        } else if (STRCMP(p, "ls", 2) == 0) {
            shellLs(fd, p);
        } else if (STRCMP(p, "mkdir", 5) == 0) {
            shellMkdir(fd, p);
        } else if (STRCMP(p, "mv", 2) == 0) {
            shellMv(fd, p);
        } else if (STRCMP(p, "nvt", 3) == 0) {
            shellNvTest(fd, p);
        } else if (STRCMP(p, "nvrt", 4) == 0) {
            shellNvReadback(fd, p);
        } else if (STRCMP(p, "ping", 4) == 0) {
            shellPing(fd, p);
        } else if (STRCMP(p, "put", 3) == 0) {
            shellPut(fd, p);
        } else if (STRCMP(p, "pwd", 3) == 0) {
            shellPwd(fd, p);
        } else if (STRCMP(p, "rm", 2) == 0) {
            shellRm(fd, p);
		} else if (STRCMP(p, "s", 1) == 0) {
			f = fopen(shellSkipBlank(p+1), "rb");
			if (f ==  NULL) printf("Cannot open file %s !!\n", shellSkipBlank(p+1));
        } else if (STRCMP(p, "ver", 3) == 0) {
            shellVer(fd, p);
        } else if (STRCMP(p, "wb", 2) == 0) {
            if (boot) shellWriteBoot(fd, p);
            else printf("Error: boot option(-b) is not on\n");
        } else if (STRCMP(p, "rb", 2) == 0) {
            if (boot) shellReadBoot(fd, p);
            else printf("Error: boot option(-b) is not on\n");
        } else if (STRCMP(p, "import", 6) == 0) {
            shellImport(fd, p);
        } else if (STRCMP(p, "id", 2) == 0) {
            shellId(fd, p);
        } else if (STRCMP(p, "q", 1) == 0) {
            goto out;
        } else if ((*p == 'h') || (*p == 'H') || (*p == '?')) {
            Usage();
        } else printf("Shell Error: unknown command <%s>\n", p);
    }

out:

#ifdef USE_READLINE
    write_history(history_file);
    history_truncate_file(history_file, 256);
#endif

    shellClose(fd);
    if (f) fclose(f);
    return 0;
}
