/*
 *              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 <sc/sc.h>
#include <sc/ios.h>
#include <ioslibc.h>
#include <boot.h>
#include <fs.h>
#include <stdarg.h>
#include <sc/usb.h>
#include <sc/shell.h>
#include <flash.h>
#include <sc/semihost_usb.h>
#include <estypes.h>
#include <es_int.h>
#include <es.h>

#include "cmd.h"
#include "shell.h"
#include "escmd.h"

IOSError
convertToPC(IOSError rv)
{
    if (rv == ISFS_ERROR_OK) return SHELL_RET_ERR_OK;
    else if (rv == ISFS_ERROR_UNKNOWN) 
        return SHELL_RET_ERR_UNKNOWN;
    else if (rv == ISFS_ERROR_ACCESS) 
        return SHELL_RET_ERR_ACCESS;
    else if (rv == ISFS_ERROR_CORRUPT)
        return SHELL_RET_ERR_CORRUPT;
    else if (rv == ISFS_ERROR_INVALID)
        return SHELL_RET_ERR_INVALID;
    else if (rv == ISFS_ERROR_NOTREADY)
        return SHELL_RET_ERR_NOTREADY; 
    else if (rv == ISFS_ERROR_EXISTS)
        return SHELL_RET_ERR_EXISTS;
    else if (rv == ISFS_ERROR_NOEXISTS)
        return SHELL_RET_ERR_NOEXISTS;
    else if (rv == ISFS_ERROR_MAXFILES)
        return SHELL_RET_ERR_MAXFILES;
    else if (rv == ISFS_ERROR_MAXBLOCKS)
        return SHELL_RET_ERR_MAXBLOCKS;
    else {
        //printf("unknown error code = %d \n", rv);
        return SHELL_RET_ERR_CMD_FAIL;
    }
}

ISFSError
myReadDir(u8 *dname, u8 *namelist, u32 *num)
{
    int len;
    ISFSError rv;

    /* handle both "/aa" and "/aa/" case */
    len = strnlen(dname, MAX_PATH_SIZE);
    if (dname[len-1] == '/' && len > 2) {
        dname[len-1] = 0;
        rv = ISFS_ReadDir(dname, namelist, num);
        dname[len-1] = '/';
    } else rv = ISFS_ReadDir(dname, namelist, num);

    return rv;
}

int
cdPath(u8 *nPath, u8 *pwd, u8 *chdir)
{
    u8  *p, *s, *e, *max;
    int pwdLen, chLen;
   
    pwdLen = strnlen(pwd, MAX_PATH_SIZE);
    chLen = strnlen(chdir, MAX_PATH_SIZE);

    if (chdir[0] != '/') {
        memcpy(nPath, pwd, pwdLen);
        p = nPath + pwdLen;
    } else  p = nPath;

    s = chdir;
    e = chdir + chLen;
    max = nPath + MAX_PATH_SIZE - 1; 
    while (s < e) {
        if (p >= max) return -1;

        if (*s == '.') {
            if (s[1] == '/' || s[1] == 0) {
                s += 2;      /* current dir */
            } else if (s[1] == '.') {
                if (s[2] == 0 || s[2] == '/') {
                    /* change to parent dir */
                    s += 3;
                    if (p <= nPath) {
                        p = nPath;
                        *p++ = '/';
                    } else {
                        if (p[-1] != '/') return -1;

                        p -= 2;
                        while (p >= nPath) {
                            if (*p == '/') break;
                            else p--;
                        }

                        if (p < nPath) p = nPath;
                        *p++ = '/';
                    }
                }
            } else return -1;
        } else *p++ = *s++;
    } 
    
    if (p < nPath) {
        p = nPath;
        *p++ = '/';
    } else if (p[-1] != '/') *p++ = '/';

    *p++ = 0;

    return p - nPath;
}

IOSError 
shellCD(IOSFd fd, int plen)
{
    u8 *param;
    int len, num;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);

    if (rv >= 0) {
        len = cdPath(shellTmp, shellPwd, param);
        if (len > 0) {
            rv = myReadDir(shellTmp, NULL, &num);
            if (rv >= 0) memcpy(shellPwd, shellTmp, len);
            rvShell = convertToPC(rv);
        } else rvShell = SHELL_RET_INVALID_PATH;
    } else {
        rvShell = (IOSError) SHELL_RET_ERR_BUS;
        IOS_Ioctl(fd, USB_MUX_STALL_CLEAR, NULL, 0,  NULL, 0);
    }

    return rvShell;
}

IOSError 
shellFormat()
{
    IOSError rv, rvShell;

    rv = ISFS_Format();
    shellPwd[0] = '/';
    shellPwd[1] = 0;
    rvShell = convertToPC(rv);

    return rvShell;
}

char buf[16384];
IOSError
shellUsage(u32 flags)
{
    *buf = 0;
    IOSError rv = IOS_GetUsage(flags, buf, sizeof(buf));
    printf("%s", buf);
    return convertToPC(rv);
}

u8 *
shellGetAbsPath(u8 *fname, u8 *buf)
{
    int len, i;

    if (fname[0] == '/') return fname;

    len = strnlen(shellPwd, MAX_PATH_SIZE);
    memcpy(buf, shellPwd, len);

    for (i=len; i<MAX_PATH_SIZE; i++) {
        buf[i] = fname[i-len];
        if (!fname[i-len]) break;
    }

    if (i >= (MAX_PATH_SIZE-1))
        return NULL;

    return buf;
}

IOSError 
shellLs(IOSFd fd, int plen, u8 *buf, int *retLen)
{
    u8 *path, *param, *np;
    int i, n, t, next, len, pathLen;
    IOSError rv, rvShell;
    IOSFd  fsFd;
    ISFSFileStats *fstats;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return  SHELL_RET_EXCEED_MAX;
        fsFd = ISFS_Open(path, ISFS_RW_ACCESS);
        if (fsFd >= 0) {
            fstats = (ISFSFileStats *) usbBuf1;
            rv = ISFS_GetFileStats(fsFd, fstats);
            if (rv == ISFS_ERROR_OK) {
                buf[0] = 'F';
                memset(buf+4, 0, 24);
                rv = ISFS_GetAttr(path, (IOSUid *) (buf+4), (IOSGid *) (buf+8), 
                         (u32*) (buf + 12), (u32*) (buf+16), (u32*) (buf+20), (u32*) (buf+24));
                *retLen = sizeof(fstats) + 28;
                memcpy(buf+28, fstats, sizeof(ISFSFileStats));
            }
            ISFS_Close(fsFd); 
        } else if(fsFd == ISFS_ERROR_INVALID) {
            buf[0] ='D';
            rv = myReadDir(path, NULL, &n);
            * ((u32*)(buf+4)) = n;
            len = strnlen(path, MAX_PATH_SIZE);
            if ((len > 1) && (path[len - 1] == '/')) path[--len] = '\0';
            ISFS_GetAttr(path, (IOSUid *) (buf+8), (IOSGid *) (buf+12), 
                         (u32*) (buf + 16), (u32*) (buf+20), (u32*) (buf+24), (u32*) (buf+28));
            pathLen = 32;
            if (n != 0) {
                rv = myReadDir(path, buf+pathLen, (u32*)(buf+4));
                next = pathLen;
                np = path + len;
                if (np[-1] != '/') {
                    *np++ = '/';
                    *np = 0;
                }
                for (i=pathLen, n=0; i<USB_BUF_SIZE-1; i++) {
                    if (buf[i] == 0) {
                        n++;
                        memcpy(np, buf+next, i-next+1);
                        if (myReadDir(path, NULL, &t) == ISFS_ERROR_OK) {
                            buf[i] = SHELL_LS_DIR;
                        } else buf[i] = SHELL_LS_FILE;
                        next = i + 1;
                    }
                    if (n >= *((u32*)(buf+4))) break;
                }
            } else i=pathLen;

            if (i>=USB_BUF_SIZE) return SHELL_RET_EXCEED_MAX;
            else *retLen = i+1;
        } else rv = fsFd;
    } else {
        rvShell = (IOSError) SHELL_RET_ERR_BUS;
        IOS_Ioctl(fd, USB_MUX_STALL_CLEAR, NULL, 0,  NULL, 0);
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError 
shellMkdir(IOSFd fd, int plen)
{
    u8 *path, *param;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return  SHELL_RET_EXCEED_MAX;
        rv = ISFS_CreateDir(path, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
                            ISFS_RW_ACCESS);
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError 
shellRm(IOSFd fd, int plen)
{
    u8 *path, *param;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return  SHELL_RET_EXCEED_MAX;
        rv = ISFS_Delete(path);
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError 
shellMv(IOSFd fd, int plen)
{
    u8 *path, *param, *npath;
    int n;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return SHELL_RET_EXCEED_MAX;
        n = strnlen(param, MAX_PATH_SIZE);
        npath = shellGetAbsPath(param+n+1, shellTmp1);
        if (npath == NULL) return SHELL_RET_EXCEED_MAX;
        if (myReadDir(path, NULL, &n) == ISFS_ERROR_OK) 
            rv = ISFS_Rename(path, npath);
        else {
            rv = shellCmdCp(path, npath);
            if (rv == ISFS_ERROR_OK) rv = ISFS_Delete(path);
        }
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

/* copy File from PC to NC */
IOSError
shellPut(IOSFd fd, int plen)
{
    u8 *path, *param;
    int n, pos=0, writeFail=0;
    IOSError rv, rvShell = SHELL_RET_ERR_OK;
    IOSFd  fsFd = -1;
    IOSMessage m;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param+4, shellTmp);
        if (path == NULL) rvShell = SHELL_RET_EXCEED_MAX;
        else {
            rv = ISFS_CreateFile(path, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
                               ISFS_RW_ACCESS);
            
            if (rv == ISFS_ERROR_OK) {
                fsFd = ISFS_Open(path, ISFS_WRITE_ACCESS);
                if (fsFd < 0) rvShell = convertToPC(fsFd);
            } else rvShell = convertToPC(rv);
        }
    } else {
        IOS_Ioctl(fd, USB_MUX_STALL_CLEAR, NULL, 0,  NULL, 0);
        rvShell = SHELL_RET_ERR_BUS;
    }

    shellTmp1[0] = rvShell;
    n = *((int *)param);
 
    if ((rvShell == SHELL_RET_ERR_OK) && (n>0)) {
        rv = IOS_ReadAsync(fd, usbBuf0, USB_BUF_SIZE, usbMq, usbReq1); 
        if ((n > USB_BUF_SIZE) && (rv == IOS_ERROR_OK))
            rv = IOS_ReadAsync(fd, usbBuf1, USB_BUF_SIZE, usbMq, usbReq2);
        pos = 0;
        IOS_Write(fd, shellTmp1, 8);
        while (pos < n) {
            rv = IOS_ReceiveMessage(usbMq, &m, IOS_MESSAGE_BLOCK);
            if (rv == IOS_ERROR_OK) {
                if (m == (IOSMessage) (usbReq1)) {
                    if (usbReq1->status > 0) {
                        if (!writeFail) {
                            rv = ISFS_Write(fsFd, usbBuf0, usbReq1->status); 
                            if (rv < usbReq1->status) {
                                printf("shellPut: write %d failed: %d\n",
                                    usbReq1->status, rv);
                                writeFail = rv;
                            }
                        }
                        pos += usbReq1->status;
                        if ((pos+USB_BUF_SIZE)<n)
                            rv = IOS_ReadAsync(fd, usbBuf0, USB_BUF_SIZE, usbMq, usbReq1);
                    } else break;
                } else if (m == (IOSMessage) (usbReq2)) {
                    if (usbReq2->status > 0) {
                        if (!writeFail) {
                            rv = ISFS_Write(fsFd, usbBuf1, usbReq2->status);
                            if (rv < usbReq2->status) {
                                printf("shellPut: write %d failed: %d\n",
                                    usbReq2->status, rv);
                                writeFail = rv;
                            }
                        }
                        pos += usbReq2->status;
                        if ((pos+USB_BUF_SIZE)<n) 
                            rv = IOS_ReadAsync(fd, usbBuf1, USB_BUF_SIZE, usbMq, usbReq2);
                        if (pos < n) IOS_Write(fd, shellTmp1, 8);
                    } else break;
                } 
            } else break;
        }
        
        if (writeFail) rv = writeFail;
        shellTmp1[0] = rvShell = convertToPC(rv <=0 ? rv : ISFS_ERROR_OK);
    } 

    if (fsFd>=0) ISFS_Close(fsFd);
    * ((int *) (shellTmp1 + 4)) = pos;
    IOS_Write(fd, shellTmp1, 8);
    
    return rvShell;
}

/* copy File from NC to PC */
IOSError
shellGet(IOSFd fd, int plen)
{
    u8 *path, *param;
    int n, rPos, len, wPos;
    IOSError rv, rvShell = SHELL_RET_ERR_OK;
    IOSFd  fsFd = -1;
    ISFSFileStats *fstats;
    IOSMessage m;

    param = usbBuf0 + MAX_CMD_SIZE;
    fstats = (ISFSFileStats *) usbBuf1;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) rvShell = SHELL_RET_EXCEED_MAX;
        else {
            fsFd = ISFS_Open(path, ISFS_READ_ACCESS);
            if (fsFd < 0) rvShell = convertToPC(fsFd); 
            else {
                rv = ISFS_GetFileStats(fsFd, fstats);
                if (rv != ISFS_ERROR_OK) rvShell = convertToPC(rv);
            } 
        }
    } else {
        IOS_Ioctl(fd, USB_MUX_STALL_CLEAR, NULL, 0,  NULL, 0);
        rvShell = SHELL_RET_ERR_BUS;
    }

    shellTmp1[0] = rvShell;
    *((int *) (shellTmp1+4)) = n = fstats->size;
    IOS_Write(fd, shellTmp1, 8);
 
    if ((rvShell == SHELL_RET_ERR_OK) && (n>0)) {
        len = n>USB_BUF_SIZE ? USB_BUF_SIZE : n;
        ISFS_Read(fsFd, usbBuf0, len);
        IOS_WriteAsync(fd, usbBuf0, len, usbMq, usbReq1);
        rPos = len;
        if (rPos < n) {
            len = (n-rPos) > USB_BUF_SIZE ? USB_BUF_SIZE : (n-rPos);
            ISFS_Read(fsFd, usbBuf1, len);
            IOS_WriteAsync(fd, usbBuf1, len, usbMq, usbReq2);
            rPos += len;
        }
        
        wPos = 0; 
        while (wPos < n) {
            rv = IOS_ReceiveMessage(usbMq, &m, IOS_MESSAGE_BLOCK);
            if (rv == IOS_ERROR_OK) { 
                wPos += USB_BUF_SIZE;
                if (rPos >= n) continue;

                len = (n-rPos) > USB_BUF_SIZE ? USB_BUF_SIZE : (n-rPos);
                rPos += len;
                if (m == (IOSMessage) (usbReq1)) {
                    ISFS_Read(fsFd, usbBuf0, len);
                    IOS_WriteAsync(fd, usbBuf0, len, usbMq, usbReq1);
                } else if (m == (IOSMessage) (usbReq2)) {
                    ISFS_Read(fsFd, usbBuf1, len); 
                    IOS_WriteAsync(fd, usbBuf1, len, usbMq, usbReq2);
                } 
            } else {
                //printf("Recv message error\n");
                break;
            }
        }
    }
    if (fsFd >= 0) ISFS_Close(fsFd); 

    return rv;
}

IOSError
shellLaunch(IOSFd fd, int plen)
{
    u8 *path, *param;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return SHELL_RET_EXCEED_MAX;
        rv = IOS_LaunchElf(path);
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError 
shellCmdCp(u8 *path, u8 *nPath)
{
    int n, len, pos;
    IOSError rv;
    IOSFd  fsRd = -1, fsWr = -1;
    ISFSFileStats *fstats;

    fstats = (ISFSFileStats *) usbBuf1;

    fsRd = ISFS_Open(path, ISFS_READ_ACCESS);
    if (fsRd < 0) {
       // printf("Cannot open source file %s\n", path);
        return fsRd;
    }
    
    rv = ISFS_CreateFile(nPath, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS,
                         ISFS_RW_ACCESS);
    if (rv < 0) {
       // printf("Cannot create target file %s\n", nPath);
        return rv;
    }
    fsWr = ISFS_Open(nPath, ISFS_WRITE_ACCESS);
    if (fsWr < 0) {
        ISFS_Close(fsRd);
        // printf("Cannot open target file %s ret=%d\n", nPath, fsWr);
        return fsWr;
    }
    rv = ISFS_GetFileStats(fsRd, fstats);
    if (rv != ISFS_ERROR_OK) return rv;

    n = fstats->size;
    for (pos = 0; pos < fstats->size; pos += USB_BUF_SIZE) {
        len = (n-pos) > USB_BUF_SIZE ? USB_BUF_SIZE : (n-pos);
        ISFS_Read(fsRd, usbBuf0, len);
        ISFS_Write(fsWr, usbBuf0, len);
    }

    if (fsRd >= 0) ISFS_Close(fsRd);
    if (fsWr >= 0) ISFS_Close(fsWr);

    return rv;
}

IOSError 
shellCp(IOSFd fd, int plen)
{
    int n;
    u8 *path, *param, *npath;
    IOSError rv, rvShell;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);
    
    if (rv >= 0) {
        path = shellGetAbsPath(param, shellTmp);
        if (path == NULL) return SHELL_RET_EXCEED_MAX;
        n = strnlen(param, MAX_PATH_SIZE);
        npath = shellGetAbsPath(param+n+1, shellTmp1);
        if (npath == NULL) return SHELL_RET_EXCEED_MAX;
        rv = shellCmdCp(path, npath);
    }

    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError
writeBoot1(IOSFd flFd, IOSFd usbFd, int bootLen, int eBlkSz, int pageSize)
{
    int pos;
    IOSError rv = ISFS_ERROR_OK;

    if ((rv = IOS_Seek(flFd, 0, IOS_SEEK_SET)) < 0) {
        printf("Failed to call flash seek ret = %d\n", rv);
        return rv;
    }

    if ((rv = IOS_Ioctl(flFd, FL_ERASE, NULL, 0, NULL, 0)) != 0) {
        printf("Failed to call flash erase = %d\n", rv);
        return rv;
    }

    if ((rv = reliableRead(usbFd, usbBuf0, bootLen)) < 0) {
        printf("Error: Usb read return %d \n", rv);
        return rv;
    }

    if (FL_LOGI_BLOCK_SIZE > bootLen)  
        memset(usbBuf0+bootLen, 0, FL_LOGI_BLOCK_SIZE - bootLen);

    for (pos = 0; pos < FL_LOGI_BLOCK_SIZE; pos+=pageSize) {
        if ((rv = IOS_Write(flFd, usbBuf0 + pos, pageSize)) < 0) {
            printf("Write to Flash page failed @ 0x%x \n", pos);
            return rv;
        }
    } 
    
    return ISFS_ERROR_OK;
}

IOSError
writeBoot2UsingES(
    IOSFd usbFd, 
    int bootLen)
{
    IOSError rv = IOS_ERROR_OK;
    int total = 0, rd;
    u8* ptr;
    u8 *certList, *ticket, *tmd, *bootApp;
    u32 certSize, tmdSize, bootAppSize;

    if (bootLen > USB_BIG_BUF_SIZE) {
        printf("buffer size not big enough for boot2 %d\n", bootLen);
        rv = IOS_ERROR_INVALID;
        goto out;
    }

    ptr = usbBuf0;
    while (total < bootLen) {
        rd = MIN(USB_BUF_SIZE, bootLen - total);

        rv = reliableRead(usbFd, ptr, rd);
        if (rv < 0) {
            printf("Failed to read %d ret = %d\n", rd, rv);
            goto out;
        }
        ptr += rd;
        total += rd;
    }

    certList = usbBuf0 + sizeof(ESWadHeader);
    certSize = ntohl(((ESWadHeader*)usbBuf0)->certSize);
    ticket = certList + certSize;
    tmd = ticket + ntohl(((ESWadHeader*)usbBuf0)->ticketSize);
    tmdSize = ntohl(((ESWadHeader*)usbBuf0)->tmdSize);
    bootApp = usbBuf0 + ntohl(((ESWadHeader*)usbBuf0)->contentOffset);
    bootAppSize = (ntohll(((ESTitleMeta*)tmd)->contents[0].size) 
                  + (ES_AES_LINE_SIZE-1)) & (~(ES_AES_LINE_SIZE-1));
    printf("certSize: %d tmdSize: %d bootAppSize: %d \n \
            certList: %08x ticket: %08x tmd: %08x bootApp: %08x\n", 
            certSize, tmdSize, bootAppSize, certList, ticket, tmd, bootApp); 

    rv = ES_ImportBoot(ticket, certList, certSize, tmd, tmdSize, certList, 
         certSize, NULL, 0, bootApp, bootAppSize);
    if (rv != ES_ERR_OK) {
        printf("Failed importing boot2 rv=%d\n", rv);
        goto out;
    } else {
        printf("import boot2 successful\n", rv);
    }

out:
    return (rv);
}

IOSError
getFlashBlkPageSize(IOSFd flFd, int *eBlkSz, int *pageSize)
{
    IOSError  rv;
    FLDevCap  *cap;

    cap = (FLDevCap *) shellTmp;
    rv = IOS_Ioctl(flFd, FL_GETCAP, NULL, 0, cap, sizeof (FLDevCap));
    if (rv != IOS_ERROR_OK) { 
        printf("Failed to get flash capabilities, rv=%d\n", rv);
        return rv;
    }

    *eBlkSz = 1 << cap->erasableBlockSzShift;
    *pageSize = 1 << cap->pageSzShift;
     
    /* check flash size and USB buffer */
    if (*eBlkSz % USB_BUF_SIZE) {
        printf("Error: Break assumption of relationship\n");
        printf("       between flash block %d and usb buffer %d \n",
               *eBlkSz, USB_BUF_SIZE);
        return ISFS_ERROR_INVALID;
    }

    if (USB_BUF_SIZE % *pageSize) {
        printf("Error: Break assumption of relationship\n");
        printf("       between usb buffer %d and flash page size %d\n",
               USB_BUF_SIZE, pageSize);
        return ISFS_ERROR_INVALID;
    }

    if (FL_LOGI_BLOCK_SIZE > USB_BUF_SIZE) {
        printf("Error: Usb buffer is too small to hold one flash logic block \n");
        return ISFS_ERROR_INVALID;
    }

    return ISFS_ERROR_OK;
}

IOSError 
shellWriteboot(IOSFd fd, int boot, int bootLen)
{
    IOSError rv = ISFS_ERROR_INVALID;
    IOSFd    flFd;
    int eBlkSz, pageSize;

    flFd = IOS_Open("/dev/flash", 0);
    if (flFd < 0) {
        printf("Failed to open flash device error=%d \n", flFd);
        rv = flFd;
        goto out;
    }    

    rv = getFlashBlkPageSize(flFd, &eBlkSz, &pageSize);
    if (rv < 0) 
        goto out;

    switch (boot) {
    case 1:
        if (bootLen > FL_LOGI_BLOCK_SIZE) {
            rv = ISFS_ERROR_INVALID;
            printf("Boot1 size(%d) is more than 1 Logical block size", bootLen);
            goto out;
        }
        rv = writeBoot1(flFd, fd, bootLen, eBlkSz, pageSize);
        break;
    case 2:
        usbBuf1[0] = SHELL_RET_ERR_OK;
        * ((int *) (usbBuf1 + 4)) = 0;
        IOS_Write(fd, usbBuf1, 8);
        rv = writeBoot2UsingES(fd, bootLen);
        break;
    default:
        rv = SHELL_RET_ERR_INVALID;
        usbBuf1[0] = rv;
        * ((int *) (usbBuf1 + 4)) = 0;
        IOS_Write(fd, usbBuf1, 8);
        break;
    }

out:
    if (flFd >= 0)  IOS_Close(flFd);
    return convertToPC(rv);
}

IOSError
readBoot1(IOSFd flFd, IOSFd usbFd, int pageSize)
{
    int pos;
    IOSError rv;

    if ((rv = IOS_Seek(flFd, 0, IOS_SEEK_SET)) < 0) {
        printf("Failed to call flash seek ret = %d\n", rv);
        return rv;
    }

    for (pos = 0; pos < FL_LOGI_BLOCK_SIZE; pos+=pageSize) {
        if ((rv = IOS_Read(flFd, usbBuf0 + pos, pageSize)) < 0) {
            printf("Read Flash page failed @ 0x%x \n", pos);
            return rv;
        }
    }

    usbBuf1[0] = SHELL_RET_ERR_OK;
    *((short *) (usbBuf1+2)) = 0;
    *((int *) (usbBuf1+4)) = FL_LOGI_BLOCK_SIZE;
    IOS_Write(usbFd, usbBuf1, 8);
    IOS_Write(usbFd, usbBuf0, FL_LOGI_BLOCK_SIZE);
    
    return ISFS_ERROR_OK;
}

IOSError 
shellReadboot(IOSFd fd, int boot)
{
    IOSError rv = ISFS_ERROR_INVALID;
    IOSFd    flFd;
    int eBlkSz, pageSize;

    flFd = IOS_Open("/dev/flash", 0);
    if (flFd < 0) {
        printf("Failed to open flash device error=%d \n", flFd);
        rv = flFd;
        goto out;
    }    

    rv = getFlashBlkPageSize(flFd, &eBlkSz, &pageSize);
    if (rv < 0) 
        goto out;

    switch (boot) {
    case 1:
        rv = readBoot1(flFd, fd, pageSize);
        break;
    default:
        rv = SHELL_RET_ERR_INVALID;
        usbBuf1[0] = rv;
        *((short *) (usbBuf1+2)) = 0;
        *((int *) (usbBuf1+4)) = 0;
        IOS_Write(fd, usbBuf1, 8);
        break;
    }

out:
    if (flFd >= 0)  IOS_Close(flFd);
    return convertToPC(rv);
}

IOSError
shellSemihostStart(IOSFd fd)
{
    USBSemihostRequest *req;

    req = (USBSemihostRequest *) usbBuf0;
    req->magic = USB_SEMI_REQ_MAGIC;
    req->len = 0;
    req->req = USB_SEMIHOST_START;

    return IOS_Write(fd, req, sizeof(USBSemihostRequest));
}

IOSError
shellSemihostEnd(IOSFd fd)
{
    USBSemihostRequest *req;

    req = (USBSemihostRequest *) usbBuf0;
    req->magic = USB_SEMI_REQ_MAGIC;
    req->len = 0;
    req->req = USB_SEMIHOST_END;

    return IOS_Write(fd, req, sizeof(USBSemihostRequest));
}

IOSError
shellImport(IOSFd fd, int plen)
{
    u8 *param;
    ESError rv;

    param = usbBuf0 + MAX_CMD_SIZE;
    rv = reliableRead(fd, param, plen);

    if (rv >= 0) {
        shellSemihostStart(fd);
        printf("importing wad file: %s\n", param);
        rv = import(param);
        shellSemihostEnd(fd);
    }

    return rv;
}

#define SHELL_KP_LEN     512
#define SHELL_ID_SYS     "/sys/id.sys"
//#define SHELL_KP_OFFS    0x8000
#define SHELL_KP_OFFS    0

IOSError
shellProgId(IOSFd fd, int len)
{
    IOSFd  fsFd = -1;
    u8 *data;
    IOSError rv;
    int barcodeLen, idLen, kpLen, totalLen, i;

    rv = reliableRead(fd, usbBuf0, len);
    IOS_NvramForceReal();
    if (rv >= 0) {
        barcodeLen = *((int *) usbBuf0);         
        idLen = *((int *) (usbBuf0+sizeof(int)));         
        kpLen = *((int *) (usbBuf0+sizeof(int)*2));
        data = usbBuf0 + sizeof(int) * 3;

        totalLen = barcodeLen + idLen + kpLen + sizeof(int) * 3;
        printf("Length = %d %d %d totalLen = %d ReadLen = %d \n",
               barcodeLen, idLen, kpLen, totalLen, len);

        if (totalLen == len) {
            /* Write ID to file /sys/id.sys */
            ISFS_Delete(SHELL_ID_SYS);
            rv = ISFS_CreateFile(SHELL_ID_SYS, 0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS); 
            if (rv == ISFS_ERROR_OK) {
                printf("Write barcode and ID to %s \n", SHELL_ID_SYS);
                rv = fsFd = ISFS_Open(SHELL_ID_SYS, ISFS_WRITE_ACCESS);
                if (rv >= 0) {
                    rv = ISFS_Write(fsFd, data+barcodeLen, idLen);
                    if (rv >= 0) {
                        shellTmp[0] = '\n';
                        ISFS_Write(fsFd, shellTmp, 1);
                    }
                    if (rv >= 0) ISFS_Write(fsFd, data, barcodeLen);
                    ISFS_Close(fsFd);
                }

                if (rv >= 0) {
                    printf("Program KiloPass\n");
                    data = data + barcodeLen + idLen;
                    for  (i=0; i<kpLen; i++) 
                        IOS_NvramWriteData(SHELL_KP_OFFS + i*8, data[i], 8);
                    rv = IOS_ERROR_OK;
                }
            }
        } else rv = ISFS_ERROR_INVALID; 
    }

    return convertToPC(rv);
}

int
shellReadId(IOSFd fd, u8 *buf)
{
    int len = -1, i;
    IOSFd  fsFd = -1;
    IOSError rv;
    u8 *data;
    ISFSFileStats *fstats;
    char *noexists = "id.sys not exist\nid.sys not exist\n";

    fsFd = ISFS_Open(SHELL_ID_SYS, ISFS_READ_ACCESS);
    IOS_NvramForceReal();
    if (fsFd >= 0) {
        fstats = (ISFSFileStats *) shellTmp;
        len = rv = ISFS_GetFileStats(fsFd, fstats);
        if (rv < 0) {
            goto out;
            printf("ISFS_GetFileStats failed \n");
        }
        if (fstats->size > (USB_BUF_SIZE - SHELL_KP_LEN)) {
            printf("ID file size is too big (%d)\n", fstats->size);
            len = -fstats->size;
            goto out;
        }
        rv = ISFS_Read(fsFd, buf, fstats->size);
        if (rv >= 0) {
            len = fstats->size;
            data = buf + len;
            data[0] = '\n';
            data++;
            for  (i=0; i<SHELL_KP_LEN; i++) 
                data[i] = IOS_NvramReadData(SHELL_KP_OFFS + i*8, 8);
            len += SHELL_KP_LEN + 1;
        } else {
            printf("Read ID file failed\n");
            len = rv;
        }
    } else {
        len = strnlen(noexists, 256);
        memcpy(buf, noexists, len);
        data = buf + len;
        for  (i=0; i<SHELL_KP_LEN; i++)
            data[i] = IOS_NvramReadData(SHELL_KP_OFFS + i*8, 8);
        len += SHELL_KP_LEN;
    }
    
out:
    if (fsFd >= 0) ISFS_Close(fsFd);

    return len;
}

#define KP_TEST_ADDR     0xfff0
IOSError
shellKpTest(int wh)
{
    IOSError rv;

    if (wh < 0 || wh > 7) rv = IOS_ERROR_INVALID;
    else {
	    IOS_NvramForceReal();
        IOS_NvramWriteData(KP_TEST_ADDR+wh, 1, 1);
        if (IOS_NvramReadData(KP_TEST_ADDR+wh, 1)) 
            rv = IOS_ERROR_OK;
        else rv = IOS_ERROR_ACCESS;
    }

    return convertToPC(rv);
}

IOSError
shellKpReadTest(char *d)
{
    IOS_NvramForceReal();
    *d = (u8) IOS_NvramReadData(KP_TEST_ADDR, 8);
    
    return IOS_ERROR_OK;
}

IOSError 
shellSetDate(char *ymd_hms)
{
    IOSError rv, rvShell;
    IOSDate *rtc;

    rtc = (IOSDate *) shellTmp;
    rtc->month  = ymd_hms[0]; 
    rtc->day    = ymd_hms[1]; 
    rtc->year   = ymd_hms[2]; 

    rtc->hour   = ymd_hms[3]; 
    rtc->minute = ymd_hms[4]; 
    rtc->second = ymd_hms[5]; 

    rv = IOS_SetDate(rtc);
    rvShell = convertToPC(rv);
    return rvShell;
}

IOSError 
shellGetDate(char *ymd_hms)
{
    IOSError rv, rvShell;
    IOSDate *rtc;

    rtc = (IOSDate *) shellTmp;
    rv = IOS_GetDate(rtc);

    ymd_hms[0] = rtc->month; 
    ymd_hms[1] = rtc->day; 
    ymd_hms[2] = rtc->year; 

    ymd_hms[3] = rtc->hour; 
    ymd_hms[4] = rtc->minute; 
    ymd_hms[5] = rtc->second; 

    rvShell = convertToPC(rv);
    return rvShell;
}
