/*
 *               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.
 *
 *  Description:
 *      This file implements file system related monitor functions
 *
 */


#include <ioslibc.h>
#include <fs.h>
#include <apputils.h>

#include <rvl/iop.h>
#include <rvl/ios.h>
#ifdef CPU_TO_BUS_ADDR
#undef CPU_TO_BUS_ADDR
#define CPU_TO_BUS_ADDR(a)  (a)
#endif


/* Dump size */
#define DUMP_SIZE               1024

/* 16KB buffer */
// static u8       *buf;
static u8       buf[ISFS_BLOCK_SIZE] __attribute__((aligned(64)));

/* Current directory */
static char     cur[ISFS_PATH_MAXLEN];



s32
isfsCmdInit(char *args, char *d)
{
    s32         rc = IOS_ERROR_OK;

    strncpy(cur, "/", ISFS_PATH_MAXLEN);

    return(rc);

}


u32
statfs(char *args, char *d)
{
    s32         rc = IOS_ERROR_OK;
    ISFSStats   stat;

    rc = ISFS_GetStats(&stat);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get FS stats, rc=%d\n", rc);
        goto statfs_out;
    }

    printf("File system statistics:\n");
    printf("Block size:         %d\n", stat.blockSize);
    printf("Free blocks:        %d\n", stat.freeBlocks);
    printf("Occupied blocks:    %d\n", stat.occupiedBlocks);
    printf("Bad blocks:         %d\n", stat.badBlocks);
    printf("Reserved blocks:    %d\n", stat.reservedBlocks);
    printf("Free inodes:        %d\n", stat.freeInodes);
    printf("Occupied inodes:    %d\n", stat.occupiedInodes);

statfs_out:

    return (rc);
}


s32
cd(char *args, char *d)
{
    s32         rc = 0;
    u32         len, num;
    ISFSError   result = ISFS_ERROR_OK;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto cd_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Make sure the directory exists by doing a read */
    result = ISFS_ReadDir(temp, NULL, &num);
    if (result != ISFS_ERROR_OK) {
        rc = -2;
        goto cd_out;
    }

    /* cd is successful, change the current directory */
    strncpy(cur, temp, ISFS_PATH_MAXLEN);

cd_out:

    if (rc == 0) {
        printf("Current directory is %s\n", cur);
    } else {
        printf("Failed to cd, rc=%d\n", rc);
    }

    return (rc);
}


s32
ls(char *args, char *d)
{
    s32         rc = 0;
    u32         num, count;
    ISFSError   result;
    u8          *list = buf;

    result = ISFS_ReadDir(cur, NULL, &num);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get the number of elements, rc=%d\n", result);
        rc = -1;
        goto ls_out;
    }

    result = ISFS_ReadDir(cur, list, &num);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to read the directory, rc=%d\n", result);
        rc = -2;
        goto ls_out;
    }

    printf("List of files/directories under %s:\n", cur);
    for (count = 0; count < num; count++) {
        printf("%s\n", list);
        list += strnlen(list, ISFS_INODE_NAMELEN) + 1;
    }

ls_out:

    if (rc != 0) {
        printf("Failed to ls, rc=%d\n", rc);
    }

    return (rc);
}


void
getAbsolutePath(char *rel, char *ab)
{
    u32     len;

    len = strnlen(rel, ISFS_PATH_MAXLEN);

    if (rel[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(ab, rel, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(ab, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                ab[cur_len] = '/';
                cur_len++;
            }
            memcpy((ab + cur_len), rel, (len + 1));
        }
    }
}


s32
cp(char *args, char *d)
{
    s32             rc = 0, fd = -1, fdSrc = -1;
    u32             size;
    ISFSError       result;
    char            *opt, *src, *dst;
    char            tempSrc[ISFS_PATH_MAXLEN], tempDst[ISFS_PATH_MAXLEN];
    u32             addr = (u32) buf, force = 0;
    u32             startw, endw, totalw = 0, startr, endr, totalr = 0;
    ISFSFileStats   stats;

    if (getNextToken(&opt, &args) == 0) {
        rc = -1;
        goto cp_out;
    }
    if (strncmp(opt, "-f", 2) == 0) {
        force = 1;
        if (getNextToken(&src, &args) == 0) {
            rc = -1;
            goto cp_out;
        }
    } else {
        src = opt;
    }
    if ((getNextToken(&dst, &args) == 0)) {
        rc = -1;
        goto cp_out;
    }

    getAbsolutePath(src, tempSrc);
    getAbsolutePath(dst, tempDst);

    fdSrc = ISFS_Open(tempSrc, ISFS_READ_ACCESS);
    if (fdSrc < 0) {
        printf("Failed to open source file %d\n", fdSrc);
        printf("Please use the put command to transfer from a remote host"
            " to the target flash\n");
        rc = -2;
        goto cp_out;
    }

    /* Open the destination file */
    result = ISFS_CreateFile(tempDst,
                        0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (result != ISFS_ERROR_OK) {
        if (result == ISFS_ERROR_EXISTS) {
            if (!force) {
                printf("File already exists, please delete first\n");
                rc = -3;
                goto cp_out;
            } else {
                result = ISFS_Delete(tempDst);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to delete %d\n", result);
                    rc = -3;
                    goto cp_out;
                }

                result = ISFS_CreateFile(tempDst,
                            0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to create file %d\n", result);
                    rc = -3;
                    goto cp_out;
                }
            }
        } else {
            printf("Failed to create file %d\n", result);
            rc = -3;
            goto cp_out;
        }
    }

    fd = ISFS_Open(tempDst, ISFS_WRITE_ACCESS);
    if (fd < 0) {
        printf("Failed to open destination file %d\n", fd);
        rc = -4;
        goto cp_out;
    }

    memset((void *)addr, 0, DUMP_SIZE);

    result = ISFS_GetFileStats(fdSrc, &stats);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file stats %d\n, result");
        rc = -5;
        goto cp_out;
    }
    size = stats.size;

    /* Read data from source to destination */
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, src, addr);
    while (size) {
        int     bytes;

        startr = IO_READ(SYS_TIMER_REG);
        result = ISFS_Read(fdSrc, (void *)addr, ISFS_BLOCK_SIZE);
        endr = IO_READ(SYS_TIMER_REG);
        if (result != ISFS_ERROR_OK) {
            printf("Failed to read %d\n", result);
            rc = -6;
            goto cp_out;
         }
        totalr += (endr - startr);

        bytes = (size > ISFS_BLOCK_SIZE) ? ISFS_BLOCK_SIZE : size;
        size -= bytes;

        startw = IO_READ(SYS_TIMER_REG);
        result = ISFS_Write(fd, (u8 *)addr, bytes);
        endw = IO_READ(SYS_TIMER_REG);
        if (result != ISFS_ERROR_OK) {
            printf("Failed to write %d\n", result);
            rc = -7;
            goto cp_out;
        }
        totalw += (endw - startw);
    }

    if (totalr > 0) {
        printf("Total read time is %d ticks\n", totalr);
    }
    if (totalw > 0) {
        printf("Total write time is %d ticks\n", totalw);
    }

cp_out:

    if (fdSrc >= 0) {
        ISFS_Close(fdSrc);
    }

    if (fd >= 0) {
        ISFS_Close(fd);
    }

    if (rc == 0) {
        printf("Copied file to %s\n", tempDst);
    } else {
        printf("Failed to cp, rc=%d\n", rc);
    }

    return (rc);
}


s32
mv(char *args, char *d)
{
    s32         rc = 0;
    char        *src, *dst;
    char        srcTemp[ISFS_PATH_MAXLEN], dstTemp[ISFS_PATH_MAXLEN];
    ISFSError   result;

    if (getNextToken(&src, &args) == 0) {
        rc = -1;
        goto mv_out;
    }

    if (getNextToken(&dst, &args) == 0) {
        rc = -2;
        goto mv_out;
    }

    getAbsolutePath(src, srcTemp);
    getAbsolutePath(dst, dstTemp);

    result = ISFS_Rename(srcTemp, dstTemp);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to rename %s to %s, rc = %d\n", srcTemp, dstTemp, rc);
        rc = -3;
        goto mv_out;
    }

mv_out:

    return (rc);
}


s32
stat(char *args, char *d)
{
    s32         rc = 0, fd = -1;
    ISFSError   result;
    char        *fname, temp[ISFS_PATH_MAXLEN];
    ISFSFileStats stats;

    if (getNextToken(&fname, &args) == 0) {
        rc = -1;
        goto stat_out;
    }

    getAbsolutePath(fname, temp);

    /* Open the file */
    fd = ISFS_Open(temp, ISFS_READ_ACCESS);
    if (fd < 0) {
        rc = -2;
        goto stat_out;
    }

    result = ISFS_GetFileStats(fd, &stats);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file stats %d\n", result);
        rc = -3;
        goto stat_out;
    }

    printf("'%s' stats:\n", fname);
    printf("  bytes:  %d\n", stats.size);
    printf("  offset: %d\n", stats.offset);

stat_out:
    if (fd >= 0) {
        ISFS_Close(fd);
    }

    return (rc);
}

static char *
access(char *s, u32 len, u32 access)
{
    switch (access) {
    case 0:
        snprintf(s, len, "NONE");
        break;
    case ISFS_READ_ACCESS:
        snprintf(s, len, "R");
        break;
    case ISFS_WRITE_ACCESS:
        snprintf(s, len, "W");
        break;
    case ISFS_RW_ACCESS:
        snprintf(s, len, "RW");
        break;
    default:
        snprintf(s, len, "ILLEGAL");
        break;
    }
    return s;
}

s32
attr(char *args, char *d)
{
    s32         rc = 0;
    ISFSError   result;
    char        *fname, temp[ISFS_PATH_MAXLEN];
    char accString[16];
    IOSUid owner;
    IOSGid group;
    u32 attributes;
    u32 ownerAcc;
    u32 groupAcc;
    u32 othersAcc;

    if (getNextToken(&fname, &args) == 0) {
        rc = -1;
        goto attr_out;
    }

    getAbsolutePath(fname, temp);

    result = ISFS_GetAttr(temp, &owner, &group, &attributes, &ownerAcc, &groupAcc, &othersAcc);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file attributes %d\n", result);
        rc = -3;
        goto attr_out;
    }

    printf("'%s' attributes:\n", fname);
    printf("  owner: 0x%x\n", owner);
    printf("  group: 0x%x\n", group);
    printf("  attributes: 0x%x\n", attributes);
    printf("  owner access: %s\n", access(accString, sizeof(accString), ownerAcc));
    printf("  group access: %s\n", access(accString, sizeof(accString), groupAcc));
    printf("  others access: %s\n", access(accString, sizeof(accString), othersAcc));

attr_out:
    return (rc);
}


s32
mkdir(char *args, char *d)
{
    s32         rc = 0;
    u32         len;
    ISFSError   result;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto mkdir_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Create the new directory */
    result = ISFS_CreateDir(temp,
          0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (result != ISFS_ERROR_OK) {
        rc = -2;
        goto mkdir_out;
    }

mkdir_out:

    if (rc == 0) {
        printf("Created directory %s\n", temp);
    } else {
        printf("Failed to create the directory, rc=%d\n", rc);
    }

    return (rc);
}


s32
rm(char *args, char *d)
{
    s32         rc = 0;
    u32         len;
    ISFSError   result;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto rm_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Try to delete as a file */
    result = ISFS_Delete(temp);
    if (result != ISFS_ERROR_OK) {
        printf("Delete returns error %d\n", result);
        rc = -2;
        goto rm_out;
    }

rm_out:

    if (rc == 0) {
        printf("Removed %s\n", temp);
    } else {
        printf("Failed to remove the file or directory, rc=%d\n", rc);
    }

    return (rc);
}


s32
format(char *args, char *d)
{
    s32     rc = ISFS_ERROR_OK;
    char    *opt;

    if (getNextToken(&opt, &args) == 0) {
        rc = -1;
        printf("Usage: format -f to force format\n");
        goto out;
    }
    if (strncmp(opt, "-f", 2) != 0) {
        rc = -1;
        printf("Usage: format -f\n");
        goto out;
    }

    rc = ISFS_Format();
    if (rc != ISFS_ERROR_OK) {
        printf("Failed to format file system, rc=%d\n", rc);
        goto format_out;
    }

    /* Set the current directory to the root directory */
    strncpy(cur, "/", ISFS_PATH_MAXLEN);

format_out:
    
    if (rc == 0) {
        printf("Formatted the file system\n");
    } else {
        printf("Failed to format, rc=%d\n", rc);
    }

out:

    return (rc);
}


