/*
 *              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 <sys/time.h>
#define STRCMP  strncasecmp
#include <sc/shell.h>
#include "utils.h"
#include "cmd.h"

char cmdBuf[16384];

char *
shellSkipBlank(char *str)
{
    while (str[0] == ' ' || str[0] == '\t') {
        str++;
    }

    return str;
}

char *
shellSkipNonBlank(char *str)
{
    while (str[0] != ' ' && str[0] != '\t' && str[0] != '\0') {
         str++;
    }

    return str;
}

int
shellNullTerminateCmd(char *str)
{
    char *eos=str;

    while (*str != '\0') {
        if (*str == '\r' || *str == '\n') {
            eos = str;
            break;
        }
        if (*str != '\t' && *str != ' ') 
            eos = str + 1;
        str++;
    }

    *eos = '\0';

    return 0;
}

char *
parse2str(char *combine, char *cmd, int *totalLen)
{
	char *p = cmd, *pn=combine, *p2;
	int len, len2;

	if (*p == '"') {
		for (len=0, p++; ;len++) {
			if (*p=='\r' || *p=='\n' || *p==0) {
				return NULL;
			}
			if (*p == '"') break;
			*pn++ = *p++;
		}
		*pn++ = 0;
	} else {
		for (len=0; ;len++) {
			if (*p=='\r' || *p=='\n' || *p==0) {
				return NULL;
			}
			if (*p == ' ' || *p == '\t') break;
			*pn++ = *p++;
		}
		*pn++ = 0;
	}

	p2 = pn;
	p = shellSkipBlank(p+1);
	for (len2=0; ;len2++) {
		if (*p=='\r' || *p=='\n' || *p==0) {
			break;
		}
		*pn++ = *p++;
	}
	if (len2 <= 0 ) return NULL;
	*pn++ = 0;

	*totalLen = len + len2 + 2;
	return p2;
}

static const char *strShellOK = "shell command succeeded";
static const char *strShellBusErr = "usb bus error";
static const char *strShellUnknown = "unknown file system error";
static const char *strShellAccess = "access failed";
static const char *strShellCorrupt = "file corrupted";
static const char *strShellInvalid = "invalid parameter";
static const char *strShellNotready = "file system not ready yet";
static const char *strShellExists = "file already exists";
static const char *strShellNoExists = "file does not exist";
static const char *strShellMaxfiles = "ran out of inodes";
static const char *strShellMaxblocks = "ran out of blocks";
static const char *strShellInvalidPath = "invalid path";
static const char *strShellExceedMax = "file path is too long";
static const char *strShellCmdFail = "command failed";
static const char *strShellWrong = "invalid error code";

const char *
shellGetErrStr(int code)
{
	if (code == SHELL_RET_ERR_OK) return strShellOK;
	else if (code == SHELL_RET_ERR_BUS) return strShellBusErr;
	else if (code == SHELL_RET_ERR_UNKNOWN) return strShellUnknown;
	else if (code == SHELL_RET_ERR_ACCESS) return strShellAccess;
	else if (code == SHELL_RET_ERR_CORRUPT) return strShellCorrupt;
	else if (code == SHELL_RET_ERR_INVALID) return strShellInvalid;
	else if (code == SHELL_RET_ERR_NOTREADY) return strShellNotready;
	else if (code == SHELL_RET_ERR_EXISTS) return strShellExists;
	else if (code == SHELL_RET_ERR_NOEXISTS) return strShellNoExists;
	else if (code == SHELL_RET_ERR_MAXFILES) return strShellMaxfiles;
	else if (code == SHELL_RET_ERR_MAXBLOCKS) return strShellMaxblocks;
	else if (code == SHELL_RET_INVALID_PATH) return strShellInvalidPath;
	else if (code == SHELL_RET_EXCEED_MAX) return strShellExceedMax;
	else if (code == SHELL_RET_ERR_CMD_FAIL) return strShellCmdFail;
	else return strShellWrong;
}

int
reliableSend(int fd, char *buf, int len)
{
	char rbuf[16];

	hostRecv(fd, rbuf, 8);
	if (rbuf[0] != SHELL_RET_ERR_OK)
		return rbuf[0];

	hostSend(fd, buf, len);
	
	return SHELL_RET_ERR_OK;
}

int
shellPing(int fd, char *cmd)
{
	static int seq = 0;
	char *npath = shellSkipBlank(cmd + 4);

	cmdBuf[0] = SHELL_REQ_PING;
	*((int *) (cmdBuf + 4)) = seq;

	if (npath[0] == 'N') cmdBuf[0] = hostSend(fd, cmdBuf, 8);
	else cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("Ping command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	hostRecv(fd, cmdBuf, 8);
	seq++;
	if (*((int *) (cmdBuf + 4)) != seq) {
		printf("Ping command out of sync = get %d expect %d\n", 
				*((int *) (cmdBuf + 4)), seq);
		return -1;
	}
	
	return 0;
}

int
shellPwd(int fd, char *cmd)
{
	cmdBuf[0] = SHELL_REQ_PWD;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("pwd command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}
		
	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("pwd command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, *((int *) (cmdBuf + 4)));
	printf("%s\n", cmdBuf);
	
	return 0;
}

int
shellDiag(int fd, char *cmd)
{
	char *tmp;

	tmp = shellSkipBlank(cmd + 4);
	if (STRCMP(tmp, "usb", 3) == 0) {
		diagUsb(fd,  shellSkipBlank(tmp + 3));
	} else if (STRCMP(tmp, "aud", 3) == 0) {
		diagAud(fd, shellSkipBlank(tmp + 3));
	} else if (STRCMP(tmp, "rtc", 3) == 0) {
	    diagRtc(fd, shellSkipBlank(tmp + 3));
	} else if (STRCMP(tmp, "flash", 5) == 0) {
		diagFlash(fd, shellSkipBlank(tmp + 3));
	} else if (STRCMP(tmp, "gba", 3) == 0) {
        diagGba(fd, shellSkipBlank(tmp + 3));
	} else {
		printf("Error: unsupport diag command <%s>\n", cmd);
	}

	return 0;
}

int
shellCd(int fd, char *cmd)
{
	char *npath;
	int len;
	
	cmdBuf[0] = SHELL_REQ_CD;
	
	npath = shellSkipBlank(cmd + 2);
	for (len=0; ;len++) {
		if (npath[len]=='\r' || npath[len]=='\n' || npath[len]==0)
			break;
	}
	npath[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("cd command failed rcving cmd = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("cd command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("cd command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	}

	return 0;
}

int
shellFormat(int fd, char *cmd)
{	
	cmdBuf[0] = SHELL_REQ_FORMAT;
	
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("format command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("format command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	return 0;
}

int
shellUsage(int fd, char *cmd)
{	
	char *p1;

	p1 = shellSkipBlank(cmd+5);
	cmdBuf[0] = SHELL_REQ_USAGE;
	*((int *)(cmdBuf+4)) = atoi(p1);
	
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("usage command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("usage command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	return 0;
}

int 
shellLs(int fd, char *cmd)
{
	int len, i, *p;
	char *path, *f;

	cmdBuf[0] = SHELL_REQ_LS;
	path = shellSkipBlank(cmd + 2);
	for (len=0; ;len++) {
		if (path[len]=='\r' || path[len]=='\n' || path[len]==0)
			break;
	}
	path[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("ls command failed rv cmd = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, path, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("ls command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("ls command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	} else {
		hostRecv(fd, cmdBuf+8, *((int *) (cmdBuf + 4)));
		if (cmdBuf[8] == 'F') {
			p = (int *) (cmdBuf+8);
			printf("%s %dBytes ", path, p[7]);
			printf("uid=0x%x gid=0x%x attr=%x own=%x grp=%d other=%d\n",
				p[1], p[2], p[3], p[4], p[5], p[6]);
		} else {
			printf("%s contains %d files\n", path, *((int *) (cmdBuf + 12)));
			p = (int *) (cmdBuf+12);
			printf("uid=0x%x gid=0x%x attr=%x own=%x grp=%d other=%d\n",
				   p[1], p[2], p[3], p[4], p[5], p[6]);
			path = f = cmdBuf+40;
            for (i=0; i<*((int *) (cmdBuf + 12)); path++) {
                if (*path == SHELL_LS_DIR) {
                    *path = 0;
                     printf("%d Dir %s \n", i+1, f);
                 } else if (*path == SHELL_LS_FILE) {
                     *path = 0;
                     printf("%d File %s \n", i+1, f);
                 } else continue;
                 f = path + 1;
                 i++;
            }
		}
	}

	return 0;
}

int 
shellMkdir(int fd, char *cmd)
{
	char *npath;
	int len;
	
	cmdBuf[0] = SHELL_REQ_MKDIR;
	
	npath = shellSkipBlank(cmd + 5);
	for (len=0; ;len++) {
		if (npath[len]=='\r' || npath[len]=='\n' || npath[len]==0)
			break;
	}
	npath[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mkdir command failed rcv cmd = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mkdir command failed rcv cmd = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mkdir command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	}

	return 0;
}

int 
shellRm(int fd, char *cmd)
{
	char *npath;
	int len;
	
	cmdBuf[0] = SHELL_REQ_RM;
	
	npath = shellSkipBlank(cmd + 2);
	for (len=0; ;len++) {
		if (npath[len]=='\r' || npath[len]=='\n' || npath[len]==0)
			break;
	}
	npath[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("rm command failed rcv cmd = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("rm command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("rm command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	}

	return 0;
}

int 
shellLaunch(int fd, char *cmd)
{
	char *npath;
	int len;
	
	cmdBuf[0] = SHELL_REQ_LAUNCH;
	
	npath = shellSkipBlank(cmd + 6);
	for (len=0; ;len++) {
		if (npath[len]=='\r' || npath[len]=='\n' || npath[len]==0)
			break;
	}
	npath[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("launch command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("launch command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("launch command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	return 0;
}

int
shellMv(int fd, char *cmd)
{
	int len;
	char *p2, *p1;

	p1 = cmdBuf + 8;
	p2 = parse2str(p1, shellSkipBlank(cmd+2), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}
	cmdBuf[0] = SHELL_REQ_MV;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mv command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, p1, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mv command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mv command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	}

	return 0;
}

int
shellPut(int fd, char *cmd)
{
	int len, slen;
	char *p2, *p1, *b;
	FILE *fp;
	struct stat sb;
	int sendReady=1;
	struct timeval tv1, tv2;
	float t;

	p1 = cmdBuf + sizeof(cmdBuf)/2;
	p2 = parse2str(p1, shellSkipBlank(cmd+3), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}
	
	if ((fp = fopen(p1, "rb")) == NULL) {
		printf("Cannot open PC file %s\n", p1);
		return -2;
	}
	fstat(fileno(fp), &sb);
	
	cmdBuf[0] = SHELL_REQ_PUT;
	*((int *) (cmdBuf + 4)) = (int) (strlen(p2)+5);
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	*((int *) (cmdBuf + 8)) = sb.st_size;
	strcpy(cmdBuf + 12, p2);
	cmdBuf[0] = reliableSend(fd, cmdBuf+8, (int) (strlen(p2)+5));
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	b = (char *) malloc(sb.st_size);
	fread(b, sb.st_size, 1, fp);
	fclose(fp);

	gettimeofday(&tv1, NULL);
	
	for (len=0; len < sb.st_size; len += sizeof(cmdBuf)) {
		if (sendReady) hostRecv(fd, cmdBuf, 8);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			printf("ERROR: %s\n", shellGetErrStr(cmdBuf[0]));
			printf("put command failed errcode(write data) = %d\n", cmdBuf[0]);
			return -sb.st_size;
		}
		sendReady = !sendReady;
		slen = sb.st_size - len;
		hostSend(fd, b+len, slen > sizeof(cmdBuf) ? sizeof(cmdBuf) : slen);
	}
	free(b);

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed errcode(write data) = %d\n", cmdBuf[0]);
		return -3;
	}

	gettimeofday(&tv2, NULL);
	t = (float)(tv2.tv_sec-tv1.tv_sec) + (tv2.tv_usec-tv1.tv_usec)/1000000.f;
	printf("Download %.1f KB %.1f sec %.1f KB/s\n", sb.st_size/1024.f, t, sb.st_size/1000.f/t);

	return 0;  
}

int
shellGet(int fd, char *cmd)
{
	int len, rlen, fsize;
	char *p2, *p1 ;
	FILE *fp;
	struct timeval tv1, tv2;
	float t;

	p1 = cmdBuf + 8;
	p2 = parse2str(p1, shellSkipBlank(cmd+3), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}
	
	if ( (fp = fopen(p2, "wb")) == NULL) {
		printf("Cannot open PC file %s\n", p1);
		return -2;
	}
	
	cmdBuf[0] = SHELL_REQ_GET;
	*((int *) (cmdBuf + 4)) = (int) (strlen(p1)+1);
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		return -1;
	} 

	cmdBuf[0] = (char) reliableSend(fd, p1, (int)(strlen(p1)+1));
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	} 

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	} 
	gettimeofday(&tv1, NULL);

	fsize = * ((int *) (cmdBuf+4));
	for (len=0; len <fsize; len+=rlen) {
		rlen = hostRecv(fd, cmdBuf, sizeof(cmdBuf));
		if (rlen <= 0) {
			printf("get command failed(fetch data)\n");
		} 
		fwrite(cmdBuf, rlen, 1, fp);
	}

	gettimeofday(&tv2, NULL);
	t = (float)(tv2.tv_sec-tv1.tv_sec) + (tv2.tv_usec-tv1.tv_usec)/1000000.f;
    if (t == 0) t = 1;
	printf("Download %.1f KB %.1f sec %.1f KB/s\n", fsize/1024.f, t, fsize/1000.f/t);
	
	fclose(fp);
	return 0;
}

int
shellCp(int fd, char *cmd)
{
	int len;
	char *p2, *p1;

	p1 = cmdBuf + 8;
	p2 = parse2str(p1, shellSkipBlank(cmd+2), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}
	cmdBuf[0] = SHELL_REQ_CP;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mv command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, p1, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("mv command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("cp command failed errcode = %d\n", cmdBuf[0]);
		return -3;
	}

	return 0;
}

int
shellReadBoot(int fd, char *cmd)
{
	int len, rlen, fsize, boot, rv=0;
	char *p2, *p1 ;
	FILE *fp;

	p1 = cmdBuf + 8;
	p2 = parse2str(p1, shellSkipBlank(cmd+2), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}
	
	boot = atoi(p1);
	if (boot > 3 || boot < 1) {
		printf("Invalid boot %d (NC only has 1, 2, 3) \n", boot);
		return -1;
	}

	if ( (fp = fopen(p2, "wb")) == NULL) {
		printf("Cannot open PC file %s\n", p2);
		return -2;
	}
	
	cmdBuf[0] = SHELL_REQ_READBOOT;
	cmdBuf[1] = (char) boot;
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);

	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("put command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		rv = -3;
		goto out;
	} 

	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("rb command failed errcode = %d\n", cmdBuf[0]);
		rv = -4;
		goto out;
	} 

	fsize = * ((int *) (cmdBuf+4));
	for (len=0; len <fsize; len+=rlen) {
		rlen = hostRecv(fd, cmdBuf, sizeof(cmdBuf));
		if (rlen <= 0) {
			printf("get command failed(fetch data)\n");
		} 
		fwrite(cmdBuf, rlen, 1, fp);

		if ((len+rlen) < fsize) { /* Read ack (in order to support flash error) */
			hostRecv(fd, cmdBuf, 8);
			if (cmdBuf[0] != SHELL_RET_ERR_OK) { 
				printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
				printf("rb command failed errcode = %d\n", cmdBuf[0]);
				rv = -len-5;
				goto out;
			}
		}
	}

out: 
	fclose(fp);
	return rv;
}

int
shellWriteBoot(int fd, char *cmd)
{
	char *p2, *p1, *b = NULL;
        char *extp;
	FILE *fp = NULL;
	struct stat sb;
	int len, slen, bootHd, boot, rv, max;

	p1 = cmdBuf + sizeof(cmdBuf)/2;
	p2 = parse2str(p1, shellSkipBlank(cmd+3), &len);
	if (p2 == NULL) {
		printf("INVALID cmd parameters\n");
		return -1;
	}

	boot = atoi(p1);
	if (boot > 2 || boot < 1) {
		printf("Invalid boot %d (NC only has 1 and 2) \n", boot);
		return -1;
	}

        /*
         * Try to prevent disasters by checking the file extension on the 
         * boot file to match as follows:
         *
         *   boot1 must be ".aes"
         *   boot2 must be ".bwf" (or ".wad" for backward compatibility)
         */
	if ((extp = strrchr(p2, '.')) == NULL) {
		printf("Invalid boot file name '%s' (no extension)\n", p2);
		return -1;
	}
	extp++;
	if (boot == 1 && strcmp(extp, "aes") != 0) {
		printf("Invalid boot file extension '%s' (should be 'aes')\n", extp);
		return -1;
	} else if (boot == 2) {
		if (strcmp(extp, "bwf") && strcmp(extp, "wad")) {
    
			printf("Invalid boot file extension '%s' (should be 'bwf')\n", extp);
			return -1;
		}
	}
	
	if ((fp = fopen(p2, "rb")) == NULL) {
		printf("Cannot open PC file '%s'\n", p2);
		return -2;
	}
	fstat(fileno(fp), &sb);
	b = (char *) malloc(sb.st_size);
	fread(b, sb.st_size, 1, fp);
	
	cmdBuf[0] = SHELL_REQ_WRITEBOOT;
	cmdBuf[1] = boot;
	*((int *) (cmdBuf + 4)) = sb.st_size;
	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("wb command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		rv = -3;
		goto out;
	}

	if (boot != 1) {
		hostRecv(fd, cmdBuf, 8);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
			printf("wb command failed errcode = %d\n", cmdBuf[0]);
			rv = -4;
			goto out;
		}
		bootHd = * ((int *) (cmdBuf + 4));
	}  else bootHd = 0;

	for (len=0; len <sb.st_size; len+=slen) {
		if (len == 0) max = sizeof(cmdBuf) - bootHd;
		else max = sizeof(cmdBuf);
		slen = (sb.st_size - len) > max ? max : sb.st_size - len;
		cmdBuf[0] = reliableSend(fd, b+len, slen);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
			printf("wb command failed errcode(write data) = %d\n", cmdBuf[0]);
			rv = -len -5;
			goto out;
		}
	}

out:
	if (b) free(b);
	if (fp) fclose(fp);
	return 0;  
}

int
shellVer(int fd, char *cmd)
{
	cmdBuf[0] = SHELL_REQ_VER;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("ver command failed errcode = %d\n", cmdBuf[0]);
		return -1;
	}
		
	hostRecv(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("ver command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	hostRecv(fd, cmdBuf, *((int *) (cmdBuf + 4)));
	printf("NC Devkit built at %s\n", cmdBuf);
	
	return 0;
}

int 
shellImport(int fd, char *cmd)
{
	char *npath;
	int len;
	
	cmdBuf[0] = SHELL_REQ_IMPORT;
	
	npath = shellSkipBlank(cmd + 6);
	for (len=0; ;len++) {
		if (npath[len]=='\r' || npath[len]=='\n' || npath[len]==0)
			break;
	}
	npath[len++] = 0;
	*((int *) (cmdBuf + 4)) = len;

	cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("import command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		return -1;
	}

	cmdBuf[0] = reliableSend(fd, npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
		printf("import command failed errcode = %d\n", cmdBuf[0]);
		return -2;
	}

	semihost(fd);

	hostRecv(fd, cmdBuf, 8);
	if (*((int*)cmdBuf) != 0) {
		printf("ERROR: import failed\n");
		printf("import command failed errcode = %d\n", *((int*)cmdBuf));
		return -2;
	}

	return 0;
}

int 
shellId(int fd, char *cmd)
{
    int len, i, count;

    cmdBuf[0] = SHELL_REQ_READ_ID;

    cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("id command failed errcode = %d\n", cmdBuf[0]);
        return -1;
    }
		
    hostRecv(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("id command failed errcode = %d\n", cmdBuf[0]);
        return -2;
    }

    len = *((int *) (cmdBuf + 4));
    hostRecv(fd, cmdBuf, len);
	
    printf("NC card id is :");
    for (i=0; i<len; i++) {
        printf("%c", cmdBuf[i]);
        if (cmdBuf[i] == '\n') break;
    }
    i++;

    printf("Bar code is:");
    for (;i<len; i++) {
        printf("%c", cmdBuf[i]);
        if (cmdBuf[i] == '\n') break;
    }
    i++;
   
    printf("KP data are: \n"); 
    for (count=0; i<len; i++) {
        printf("%2.2x", (unsigned char) cmdBuf[i]);
        count++;
        if (count == 16) {
            printf("\n");
            count = 0;
        }    
    }
	
    return 0;
}

int 
shellNvTest(int fd, char *cmd)
{
    int which = 0;
    char *param = shellSkipBlank(cmd + 3);

    which = atoi(param);
    if (which < 0 || which > 7) {
        printf("Invalid NvRam Test, should be 0-7\n");
        return -1;
    } 
        
    cmdBuf[0] = SHELL_REQ_KP_TEST;
    *((int *) (cmdBuf + 4)) = which;
    cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("Nvram test = %d\n", cmdBuf[0]);
        return -2;
    }
        
    hostRecv(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("nvram test failed errcode = %d\n", cmdBuf[0]);
        return -3;
    } else printf("Nvram test bit %d passed\n", which);

    return 0;
}

int 
shellNvReadback(int fd, char *cmd)
{
    int i;

    cmdBuf[0] = SHELL_REQ_KP_TEST_READ;
    cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("Nvram test readback rv = %d\n", cmdBuf[0]);
        return -1;
    }
        
    hostRecv(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("Nvram test readback failed rv = %d\n", cmdBuf[0]);
        return -2;
    } else {
        for (i=0; i<8; i++) 
            printf("NvRam bit%d = %d \n", i, (cmdBuf[4] & (1<<i)) ? 1 : 0);
    }

    return 0;
}

int 
shellDate(int fd, char *cmd)
{
    int year, month, day, hour, min, sec, get=0;
    char *d = shellSkipBlank(cmd + 4);

    if (d[0] == '\r' || d[0] == '\n' || d[0] == 0) {
        get = 1;
    } else {
        if (d[2] != '/' || d[5] != '/' || d[8] != ' ' || d[11] != ':' || d[14] != ':') {
            printf("Invalid format. Should be: MM/DD/YY hh:mm:ss\n");
            return -1;
        }

        month = (d[0] - '0') * 10 + (d[1] - '0');
        day = (d[3] - '0') * 10 + (d[4] - '0');
        year = (d[6] - '0') * 10 + (d[7] - '0');

        hour = (d[9] - '0') * 10 + (d[10] - '0');
        min = (d[12] - '0') * 10 + (d[13] - '0');
        sec = (d[15] - '0') * 10 + (d[16] - '0');

        if ((year > 99) || (year < 0) || (month > 12) || (month < 1) || 
            (day > 31)  || (day < 1)  || (hour > 23) || (hour < 0)   || 
            (min > 59)  || (min < 0)  || (sec > 59)  || (sec < 0)) {
            printf("Invalid date. %02d/%02d/%02d %02d:%02d:%02d\n", 
                    month, day, year, hour, min, sec);
            return -2;
        }
        
        cmdBuf[2] = month;
        cmdBuf[3] = day;
        cmdBuf[4] = year;
        cmdBuf[5] = hour;
        cmdBuf[6] = min;
        cmdBuf[7] = sec;
    }

    cmdBuf[0] = get ? SHELL_REQ_GET_DATE : SHELL_REQ_SET_DATE;
    cmdBuf[0] = reliableSend(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("date cmd rv = %d\n", cmdBuf[0]);
        return -3;
    }
        
    hostRecv(fd, cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        printf("ERROR: %s \n", shellGetErrStr(cmdBuf[0]));
        printf("Date cmd failed rv = %d\n", cmdBuf[0]);
        return -4;
    } else {
        if (get) 
            printf("NC Date: %02d/%02d/%02d %02d:%02d:%02d\n",
                   cmdBuf[2], cmdBuf[3], cmdBuf[4], cmdBuf[5], cmdBuf[6], cmdBuf[7]);
    }
    return 0;
}

