/*
 *              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 "stdafx.h"
#include "windows.h"
#include "dwusb.h"
#include <sys/stat.h>
#include "sc/shell.h"

char cmdBuf[16384], tmpBuf[16384];

extern int  shellGet4;
int
reliableSend(char *buf, int len)
{
	char rbuf[16];

	if (shellGet4) shellGet4 = 0;
	else hostRecv(rbuf, 8);

	if (rbuf[0] != SHELL_RET_ERR_OK)
		return rbuf[0];

	hostSend(buf, len);
	return SHELL_RET_ERR_OK;
}

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;
}

extern char usbBuf[1024];
int
shellVer(char *cmd, char *ver)
{
	cmdBuf[0] = SHELL_REQ_VER;

	cmdBuf[0] = reliableSend(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: ver send command failed errcode = %d", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}
		
	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: ver command failed errcode = %d", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	hostRecv(cmdBuf, *((int *) (cmdBuf + 4)));
	sprintf(usbBuf, "<Download PC> INFO: NC Devkit built at %s", cmdBuf);
	memcpy(ver, cmdBuf, 8);
	dbgPrintf(usbBuf);
	
	return 0;
}

int 
shellImport(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(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: import command send failed rcv cmd errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	cmdBuf[0] = reliableSend(npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: import command send2 failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	if (semihost()) return -3;

	hostRecv(cmdBuf, 8);
	if (*((int*)cmdBuf) != 0) {
		sprintf(usbBuf, "<Download PC> Error: import command back failed errcode = %d\n", *((int*)cmdBuf));
		dbgPrintf(usbBuf);
		return -4;
	}

	return 0;
}

int
shellWriteBoot(char *cmd)
{
	char *p2, *p1, *b = NULL;
	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) {
		dbgPrintf("<Download PC> Error: INVALID cmd parameters");
		return -1;
	}

	boot = atoi(p1);
	if (boot > 3 || boot < 1) {
		sprintf(usbBuf,"<Download PC> Error: Invalid boot %d (NC only has 1, 2, 3)", boot);
		dbgPrintf(usbBuf);
		return -1;
	}
	
	if ((fp = fopen(p2, "rb")) == NULL) {
		sprintf(usbBuf, "<Download PC> Error: Cannot open PC file %s", p2);
		dbgPrintf(usbBuf);
		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(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: wb command failed rcv cmd errcode = %d", cmdBuf[0]);
		dbgPrintf(usbBuf);
		rv = -3;
		goto out;
	}

	if (boot != 1) {
		hostRecv(cmdBuf, 8);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			sprintf(usbBuf, "<Download PC> Error: wb command failed errcode = %d", cmdBuf[0]);
			dbgPrintf(usbBuf);
			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(b+len, slen);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			sprintf(usbBuf, "<Download PC> Error: wb command failed errcode(write data) = %d", cmdBuf[0]);
			dbgPrintf(usbBuf);
			rv = -len -5;
			goto out;
		}
	}

out:
	if (b) free(b);
	if (fp) fclose(fp);
	return 0;  
}

int
shellFormat(char *cmd)
{	
	cmdBuf[0] = SHELL_REQ_FORMAT;
	
	cmdBuf[0] = reliableSend(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: format command failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: format command2 failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	return 0;
}

int 
shellMkdir(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(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: mkdir command failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	cmdBuf[0] = reliableSend(npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: mkdir send path errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: mkdir command2 failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -3;
	}

	return 0;
}

int
saveIds(FILE *fp, char *id, char *kpid)
{
	char *p;
	int ch, count;

	p = id;
	while (!feof(fp)) {
		ch = fgetc(fp);
		if (feof(fp)) {
			dbgPrintf("Invalid id file format");
			fclose(fp);
			return -1;
		}

		if (ch == '\n' || ch == '\r') break;
		*p++ = ch;
	}

	count = 0;
	p = kpid;
	while (!feof(fp)) {
		ch = fgetc(fp);
		if (feof(fp)) break;

		if (ch >= '0' && ch <= '9') ch = ch - '0';
		else if (ch >= 'a' && ch <= 'f') ch = ch - 'a' + 10;
		else if (ch >= 'A' && ch <= 'F') ch = ch - 'A' + 10;
		else continue;

		if (count) {
			*p = ((*p) << 4) | ch;
			count = 0;
			p++;
		} else {
			*p = ch;
			count++;
		}
	}
	fclose(fp);

	return 0;
}


int
shellProgId(char *barcode, char *idFile, int verify)
{
	FILE *fp = NULL;
	char *p, buf[32], *data;
	int barLen, idLen, kpLen, *pLen, ch, count, totalLen, i;

	barLen = strlen(barcode);
	if ((fp = fopen(idFile, "rb")) == NULL) {
		sprintf(usbBuf, "<Download PC> Error: Cannot open id file %s", idFile);
		dbgPrintf(usbBuf);
		return -1;
	}

	p = cmdBuf + sizeof(int) * 3;
	memcpy(p, barcode, barLen);
	p += barLen;

	idLen = 0;
	while (!feof(fp)) {
		ch = fgetc(fp);
		if (feof(fp)) {
			dbgPrintf("Invalid id file format");
			fclose(fp);
			return -2;
		}

		if (ch == '\n' || ch == '\r') break;
		*p++ = ch;
		idLen++;
	}

	count = kpLen = 0;
	while (!feof(fp)) {
		ch = fgetc(fp);
		if (feof(fp)) break;

		if (ch >= '0' && ch <= '9') ch = ch - '0';
		else if (ch >= 'a' && ch <= 'f') ch = ch - 'a' + 10;
		else if (ch >= 'A' && ch <= 'F') ch = ch - 'A' + 10;
		else continue;

		if (count) {
			*p = ((*p) << 4) | ch;
			count = 0;
			p++;
			kpLen++;
		} else {
			*p = ch;
			count++;
		}
	}
	fclose(fp);

	pLen = (int *) cmdBuf;
	*pLen++ = barLen;
	*pLen++ = idLen;
	*pLen++ = kpLen;
	totalLen = barLen + idLen + kpLen + sizeof(int)*3;

	buf[0] = SHELL_REQ_PROG_ID;
	*((int *) (buf + 4)) = totalLen;
	buf[0] = reliableSend(buf, 8);
	if (buf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: send Prog ID return = %d\n", buf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	cmdBuf[0] = reliableSend(cmdBuf, totalLen);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: send id data failed", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -3;
	}

	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: program id failed = %d", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -4;
	}

	if (verify) {
		ch = shellReadId(tmpBuf);
		if ((ch <= 0) || (ch < totalLen - 10)) {
			sprintf(usbBuf, "<Download PC> Error: read id back length (%d) is wrong", ch);
			dbgPrintf(usbBuf);
			return -5;
		} 

		p = cmdBuf + sizeof(int) * 3;
		if (memcmp(tmpBuf, p+barLen, idLen) != 0) {
			p[barLen + idLen] = 0;
			tmpBuf[idLen] = 0;
			sprintf("<Download PC> Error: program id = %s readback id = %s", 
				    p+barLen, tmpBuf);
			dbgPrintf(usbBuf);
			return -6;
		}

		if (tmpBuf[idLen] != '\n') {
			dbgPrintf("<Download PC> Error: id's seperator is wrong");
			return -7;
		}

		p = tmpBuf+idLen+1;
		if (memcmp(p, barcode, barLen) != 0) {
			p[barLen] = 0;
			sprintf("<Download PC> Error: barcode = %s readback = %s", p, barcode);
			dbgPrintf(usbBuf);
			return -8;
		}

		if (p[barLen] != '\n') {
			dbgPrintf("<Download PC> Error: barcode seperate is wrong");
			return -9;
		}

		p = tmpBuf+idLen+barLen+2;
		data = cmdBuf + sizeof(int) * 3 + idLen + barLen;
		for (i=ch=0; i<kpLen; i++) {
			if (p[i] != data[i]) {
				sprintf(usbBuf, "<Download PC> Error: data @%d  readback = 0x%x exp = 0x%x", 
					            i, (unsigned char) p[i], (unsigned char) data[i]);
				dbgPrintf(usbBuf);
				ch++;
			}
		}
	}

	return (ch==0) ? ch : -ch-10;  
}

int
shellReadId(char *buf)
{
	int len;

	cmdBuf[0] = SHELL_REQ_READ_ID;
	cmdBuf[0] = reliableSend(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: send Read ID return = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	hostRecv(cmdBuf, 8);
	len = *((int *) (cmdBuf + 4));
	if ((cmdBuf[0] != SHELL_RET_ERR_OK) || (len <= 0)){
		sprintf(usbBuf, "<Download PC> Error: READ id = %d len=%d\n", cmdBuf[0], len);
		dbgPrintf(usbBuf);
		return -4;
	}

	if ((cmdBuf[0] != SHELL_RET_ERR_OK)) return -5;

	hostRecv(buf, len);
	return len;
}

int
shellPut(char *cmd)
{
	int len, slen;
	char *p2, *p1, *b;
	FILE *fp;
	struct stat sb;
	int sendReady=1;

	p1 = cmdBuf + sizeof(cmdBuf)/2;
	p2 = parse2str(p1, shellSkipBlank(cmd+3), &len);
	if (p2 == NULL) {
		dbgPrintf("<Download PC> Error:INVALID put command parameters\n");
		return -1;
	}
	
	if ((fp = fopen(p1, "rb")) == NULL) {
		sprintf(usbBuf, "<Download PC> Error: Cannot open PC file %s\n", p1);
		dbgPrintf(usbBuf);
		return -2;
	}
	fstat(fileno(fp), &sb);
	
	cmdBuf[0] = SHELL_REQ_PUT;
	*((int *) (cmdBuf + 4)) = (int) (strlen(p2)+5);
	cmdBuf[0] = reliableSend(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: put command failed rcv cmd errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	*((int *) (cmdBuf + 8)) = sb.st_size;
	strcpy(cmdBuf + 12, p2);
	cmdBuf[0] = reliableSend(cmdBuf+8, (int) (strlen(p2)+5));
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: put command failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	b = (char *) malloc(sb.st_size);
	fread(b, sb.st_size, 1, fp);
	fclose(fp);

	for (len=0; len < sb.st_size; len += sizeof(cmdBuf)) {
		if (sendReady) hostRecv(cmdBuf, 8);
		if (cmdBuf[0] != SHELL_RET_ERR_OK) {
			free(b);
			sprintf(usbBuf, "<Download PC> Error: put command failed errcode(write data) = %d\n", cmdBuf[0]);
			dbgPrintf(usbBuf);
			return -sb.st_size;
		}
		sendReady = !sendReady;
		slen = sb.st_size - len;
		hostSend(b+len, slen > sizeof(cmdBuf) ? sizeof(cmdBuf) : slen);
	}
	free(b);

	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: put command failed errcode(write data) = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -3;
	}

	return 0;  
}

int 
shellRm(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(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: rm command failed rcv cmd = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -1;
	}

	cmdBuf[0] = reliableSend(npath, len);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: rm command failed errcode = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -2;
	}

	hostRecv(cmdBuf, 8);
	if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: rm command failed errcode2 = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
		return -3;
	}

	return 0;
}

int
checkKpProg(char *dir, char *id, char *kpid)
{
	FILE *f;
	int len, i, count, zero, same;
	char *p = kpid;
	char buf[1024];

	dbgPrintf("<Download PC> Info: Kilopass ID checkup");
	len = shellReadId(tmpBuf);

	if (len <= 0) { 
		dbgPrintf("<Download PC> Info: add id.sys try again");
		sprintf(buf, "%s\\sys\\id.sys", dir);
		f = fopen(buf, "wb");
		if (f == NULL) {
			dbgPrintf("<Download PC> Error: cannot create local id.sys");
			return -1;
		}
		fprintf(f, "%s\nN/A", id);
		fclose(f);
		sprintf(buf, "put %s\\sys\\id.sys /sys/id.sys", dir);
		if (shellPut(buf)) 
			return -2;

		len = shellReadId(tmpBuf);
		if (len <=0) {
			dbgPrintf("<Download PC> Error: 2nd try read ID also failed");
			return -3;
		}
	}

	if (len >= MAX_KP_LEN) {
		dbgPrintf("<Download PC> Error: kp read id is too large...");
		return -3;
	}

	for (i=count=0; i<len; i++) {
		if (tmpBuf[i] == '\n') count++;

		if (count == 2) break;
	}

	if (i>=len) {
		dbgPrintf("<Download PC> Error: no id data");
		return -4;
	}
	
	for (i=i+1, zero=same=1; i<len; i++, p++) {
		if (tmpBuf[i] != 0) zero = 0;
		if (tmpBuf[i] != *p) same = 0;
	}

	if (zero) return KP_NOT_PROG;
	if (same) return KP_MATCH_DONE;

	dbgPrintf("<Download PC> Error: Kilopass already programmed on this NC card");
	return -5;
}

int 
shellDate(char *cmd, char *ret)
{
    int year, month, day, hour, min, sec, get=0, i;
    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] != ':') {
			sprintf(usbBuf, "<Download PC> Invalid format %s. Should be: MM/DD/YY hh:mm:ss",d); 
			dbgPrintf(usbBuf);
            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)) {
            sprintf(usbBuf, "<Download PC> Invalid date. %02d/%02d/%02d %02d:%02d:%02d\n", 
                    month, day, year, hour, min, sec);
			dbgPrintf(usbBuf);
            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(cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
        sprintf(usbBuf, "<Download PC> Error: date failed rcv cmd = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
        return -3;
    }
        
    hostRecv(cmdBuf, 8);
    if (cmdBuf[0] != SHELL_RET_ERR_OK) {
		sprintf(usbBuf, "<Download PC> Error: date2 failed rcv cmd = %d\n", cmdBuf[0]);
		dbgPrintf(usbBuf);
        return -4;
    } else {
        if (get) {
			if (ret != NULL) 
				for (i=0; i<6; i++) ret[i] = cmdBuf[i+2];
            sprintf(usbBuf, "<DownloadPc> NC Date: %02d/%02d/%02d %02d:%02d:%02d\n",
                   cmdBuf[2], cmdBuf[3], cmdBuf[4], cmdBuf[5], cmdBuf[6], cmdBuf[7]);
			dbgPrintf(usbBuf);
		}
    }

    return 0;
}
