/*
 *               Copyright (C) 2006, 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 <iostypes.h>
#include <ios.h>
#include <ioslibc.h>
#include <apputils.h>
#include <sys.h>
#include <ee.h>


#define STACK_SIZE      4096              
const u8                _initStack[STACK_SIZE];
const u32               _initStackSize = sizeof(_initStack);
const u32               _initPriority = 11;


#define LINE_SIZE       256


static IOSError readEE(char *args, char *d);
static IOSError writeEE(char *args, char *d);
static IOSError eraseEE(char *args, char *d);
static IOSError writeEEAll(char *args, char *d);
static IOSError eraseEEAll(char *args, char *d);
static IOSError backupEE(char *args, char *d);
static IOSError restoreEE(char *args, char *d);
static IOSError getVersion(char *args, char *d);
static IOSError incVersion(char *args, char *d);
static IOSError clearBoot2Version(char *args, char *d);
static IOSError writeSS(char *args, char *d);


static Command commands[] = {
    {"help",    help,
        "help                   - Print this message", commands},
    {"read",  readEE,
        "read addr [count]      - Read one or more half-words starting at addr", 0},
    {"write", writeEE,
        "write addr val [count] - Write one or more half-words starting at addr", 0},
    {"writeAll", writeEEAll,
        "writeAll val           - Write value too all of EEPROM", 0},
    {"eraseEE", eraseEE,
        "erase addr [count]     - Erase one or more half-words starting at addr", 0},
    {"eraseAll", eraseEEAll,
        "eraseAll               - Erase all of EEPROM", 0},
    {"backup", backupEE,
        "backup filename        - Backup EEPROM content to file", 0},
    {"restore", restoreEE,
        "restore filename       - Restore EEPROM content from file", 0},
    {"clearBoot2Version", clearBoot2Version,
        "clearBoot2Version      - Clear all boot2 versioning info", 0},
    {"writeSS", writeSS,
        "writeSS val            - Write SS (spread spectrum) config value", 0},
    {"getVersion", getVersion,
        "getVersion <-o> <-c> <-s> <-f> - Get the specified version", 0},
    {"incVersion", incVersion,
        "incVersion <-o> <-c> <-s> <-f> - Increment the specified version", 0},
    {0},
};


static IOSError
readEE(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, value, count;
    char *ptr;

    /* Get half-word address */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: read addr [count]\n");
        goto readEE_out;
    }
    addr = asciiToInt(ptr);

    /* Get count */
    if (getNextToken(&ptr, &args) == 0) {
        count = 1;
    }
    else {
        count = asciiToInt(ptr);
        if (addr+count > 128) {              /* 92 */
            count = 128-addr;
            printf("Resetting count to %d\n", count);
        }
    }

    for (i = 0; i < count; i++) {
        /* Read from EEPROM */
        rc = EE_RdCmd(addr+i, &value);
        if (rc != IOS_ERROR_OK) {
            goto readEE_out;
        }
        value &= 0xffff;
        printf("EEPROM[%03d] = 0x%04x\n", addr+i, value);
    }


readEE_out:

    if (rc != IOS_ERROR_OK) {
        printf("readEE failed, rc=%d\n", rc);
    }

    return (rc);

}  /* readEE */


static IOSError
writeEE(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, value, count;
    char *ptr;

    /* Get half-word starting address */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: write addr value [count]\n");
        goto writeEE_out;
    }
    addr = asciiToInt(ptr);

    /* Get half-word value */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: write addr value [count]\n");
        goto writeEE_out;
    }
    value = asciiToInt(ptr);
    value &= 0xffff;

    /* Get count */
    if (getNextToken(&ptr, &args) == 0) {
        count = 1;
    }
    else {
        count = asciiToInt(ptr);
        if (addr+count > 128) {              /* 92 */
            count = 128-addr;
            printf("Resetting count to %d\n", count);
        }
    }

    for (i = 0; i < count; i++) {
        /* Enable write */
        rc = EE_WenCmd();
        if (rc != IOS_ERROR_OK) {
            goto writeEE_out;
        }

        /* Write to EEPROM */
        rc = EE_WrCmd(addr+i, value);
        if (rc != IOS_ERROR_OK) {
            goto writeEE_out;
        }

        /* Disable write */
        rc = EE_WdsCmd();
        if (rc != IOS_ERROR_OK) {
            goto writeEE_out;
        }

        printf("EEPROM[%03d] <= 0x%04x\n", addr+i, value);
    }

writeEE_out:

    if (rc != IOS_ERROR_OK) {
        printf("writeEE failed, rc=%d\n", rc);
    }

    return (rc);

}  /* writeEE */


static IOSError
eraseEE(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, count;
    char *ptr;

    /* Get half-word address */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: erase addr [count]\n");
        goto eraseEE_out;
    }
    addr = asciiToInt(ptr);

    /* Get count */
    if (getNextToken(&ptr, &args) == 0) {
        count = 1;
    }
    else {
        count = asciiToInt(ptr);
        if (addr+count > 128) {              /* 92 */
            count = 128-addr;
            printf("Resetting count to %d\n", count);
        }
    }

    for (i = 0; i < count; i++) {
        /* Enable write */
        rc = EE_WenCmd();
        if (rc != IOS_ERROR_OK) {
            goto eraseEE_out;
        }

        /* Erase value in EEPROM */
        rc = EE_EraseCmd(addr+i);
        if (rc != IOS_ERROR_OK) {
            goto eraseEE_out;
        }

        /* Disable write */
        rc = EE_WdsCmd();
        if (rc != IOS_ERROR_OK) {
            goto eraseEE_out;
        }

        printf("EEPROM[%03d] => Erased\n", addr+i);
    }

eraseEE_out:

    if (rc != IOS_ERROR_OK) {
        printf("eraseEE failed, rc=%d\n", rc);
    }

    return (rc);
}  /* eraseEE */


static IOSError
writeEEAll(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 value;
    char *ptr;

    /* Get half-word value */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: writeAll val -f\n");
        goto writeEEAll_out;
    }
    value = asciiToInt(ptr);
    value &= 0xffff;

    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: writeAll val -f\n");
        goto writeEEAll_out;
    }
    if (strncmp(ptr, "-f", 2) != 0) {
        printf("Usage: writeAll val -f\n");
        goto writeEEAll_out;
    }

    /* Enable write */
    rc = EE_WenCmd();
    if (rc != IOS_ERROR_OK) {
        goto writeEEAll_out;
    }

    /* Write to all of EEPROM */
    rc = EE_WralCmd(value);
    if (rc != IOS_ERROR_OK) {
        goto writeEEAll_out;
    }

    /* Disable write */
    rc = EE_WdsCmd();
    if (rc != IOS_ERROR_OK) {
        goto writeEEAll_out;
    }

    printf("Written 0x%x to all of EEPROM\n", value);

writeEEAll_out:

    if (rc != IOS_ERROR_OK) {
        printf("writeEEAll failed, rc=%d\n", rc);
    }

    return (rc);

}  /* writeEEAll */


static IOSError
eraseEEAll(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;

    char *ptr;

    /* Get force option */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: eraseAll -f\n");
        goto eraseEEAll_out;
    }
    if (strncmp(ptr, "-f", 2) != 0) {
        printf("Usage: eraseAll -f\n");
        goto eraseEEAll_out;
    }

    /* Enable write */
    rc = EE_WenCmd();
    if (rc != IOS_ERROR_OK) {
        goto eraseEEAll_out;
    }

    /* Erase value in EEPROM */
    rc = EE_EralCmd();
    if (rc != IOS_ERROR_OK) {
        goto eraseEEAll_out;
    }

    /* Disable write */
    rc = EE_WdsCmd();
    if (rc != IOS_ERROR_OK) {
        goto eraseEEAll_out;
    }

    printf("Erase all of EEPROM\n");

eraseEEAll_out:

    if (rc != IOS_ERROR_OK) {
        printf("eraseEEAll failed, rc=%d\n", rc);
    }

    return (rc);

}  /* eraseEEAll */


#define LINE_FORMAT "EEPROM[000] = 0x0000"

static IOSError
backupEE(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, value, bytes, count;
    char *fname;
    FILE *fp = NULL;
    char buf[36];

    /* Get filename */
    if (getNextToken(&fname, &args) == 0) {
        printf("Usage: backup filename\n");
        goto backupEE_out;
    }

    fp = fopen(fname, "wb");
    if (fp == NULL) {
        printf("Cannot open file %s\n", fname);
        rc = -1;
        goto backupEE_out;
    }
    bytes = sizeof(LINE_FORMAT);
    
    printf("Backup to file %s\n", fname);

    addr = 0;
    count = 128;
    for (i = 0; i < count; i++) {
        memset(buf, 0, sizeof(buf));
        value = 0;
        /* Read from EEPROM */
        rc = EE_RdCmd(addr+i, &value);
        if (rc != IOS_ERROR_OK) {
            goto backupEE_out;
        }
        value &= 0xffff;
        snprintf(buf, sizeof(buf), "EEPROM[%03d] = 0x%04x", addr+i, value);
        buf[bytes-1] = 0x0d;   /* Add CRLF characters */
        buf[bytes] = 0x0a; 
        printf("%s", buf);

        fwrite((void *)buf, bytes+1, 1, fp);

    }  /* while */

backupEE_out:

    if (fp) fclose(fp);

    if (rc != IOS_ERROR_OK) {
        printf("backupEE failed, rc=%d\n", rc);
    }

    return (rc);

}  /* backupEE */


static IOSError
restoreEE(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, bytes, count;
    s32 size, value;
    char *fname, *ptr;
    FILE *fp = NULL;
    char buf[80];
    char *line = NULL;

    /* Get filename */
    if (getNextToken(&fname, &args) == 0) {
        printf("Usage: restore filename\n");
        goto restoreEE_out;
    }

    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf("Cannot open file %s\n", fname);
        rc = -1;
        goto restoreEE_out;
    }
    size = flen(fp);
    printf("Restore from file %s, len=%d\n", fname, size);
    
    addr  = 0;
    count = 1;
    bytes = 7;

    /* Since there is no fgets and scanf only supports %s and %d, improvise */
    while (1) {
        for (i = 0; i < sizeof(buf) - 1; ++i) {
            buf[i] = 0;
            fread(buf+i, 1, 1, fp);
            if (buf[i] == '\r') {
                buf[i] = 0;
                continue;
            }
            if (buf[i] == '\n' || buf[i] == '\0') {
                buf[i] = 0;
                break;
            }
        }
        if (!*buf) break;

        /* Expect each line to have this format: "EEPROM[000] = 0x0000" */
        line = buf;
        // printf("buf: %s\n", line);

        /* Skip the "EEPROM[xxx]" section */
        if (getNextToken(&ptr, &line) == 0) {
            printf("Error: invalid format: (%s)\n", line);
            goto restoreEE_out;
        }
        /* Skip the "=" */
        if (getNextToken(&ptr, &line) == 0) {
            printf("Error: invalid format: (%s)\n", line);
            goto restoreEE_out;
        }
        /* Get the value */
        if (getNextToken(&ptr, &line) == 0) {
            printf("Error: invalid format: (%s)\n", line);
            goto restoreEE_out;
        }
        value = asciiToInt(ptr);

        /* Enable write */
        rc = EE_WenCmd();
        if (rc != IOS_ERROR_OK) {
            goto restoreEE_out;
        }

        printf("EEPROM[%03d] <= 0x%04x\n", addr, value);

        /* Write to EEPROM */
        rc = EE_WrCmd(addr, value);
        if (rc != IOS_ERROR_OK) {
            goto restoreEE_out;
        }

        /* Disable write */
        rc = EE_WdsCmd();
        if (rc != IOS_ERROR_OK) {
            goto restoreEE_out;
        }

        addr++;             /* Increment address index */

    }  /* while */


restoreEE_out:

    if (fp) fclose(fp);

    if (rc != IOS_ERROR_OK) {
        printf("restoreEE failed, rc=%d\n", rc);
    }

    return (rc);

}  /* restoreEE_out */


static IOSError
getVersion(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    char *ptr;
    u32 os = 0, ca = 0, signer = 0, sfs = 0;

    while (getNextToken(&ptr, &args) != 0) {
        if (memcmp(ptr, "-o", 2) == 0) {
            os = 1;
        } else if (memcmp(ptr, "-c", 2) == 0) {
            ca = 1;
        } else if (memcmp(ptr, "-s", 2) == 0) {
            signer = 1;
        } else if (memcmp(ptr, "-f", 2) == 0) {
            sfs = 1;
        } else {
            rc = IOS_ERROR_INVALID;
            goto getVersion_out;
        }
    }

    if (os) {
        rc = EE_GetOsVersion();
        if (rc < 0) {
            goto getVersion_out;
        }
        printf("OS version: %d\n", rc);
    }

    if (ca) {
        rc = EE_GetCaCrlVersion();
        if (rc < 0) {
            goto getVersion_out;
        }
        printf("CA CRL version: %d\n", rc);
    }

    if (signer) {
        rc = EE_GetSignerCrlVersion();
        if (rc < 0) {
            goto getVersion_out;
        }
        printf("Signer CRL version: %d\n", rc);
    }

    if (sfs) {
        rc = EE_GetSfsVersion();
        if (rc < 0) {
            goto getVersion_out;
        }
        printf("SFS version: %d\n", rc);
    }

    rc = IOS_ERROR_OK;

getVersion_out:

    if (rc != IOS_ERROR_OK) {
        printf("getVersion failed, rc=%d\n", rc);
    }

    return (rc);

}  /* getVersion */


static IOSError
incVersion(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    char *ptr;
    u32 os = 0, ca = 0, signer = 0, sfs = 0;

    while (getNextToken(&ptr, &args) != 0) {
        if (memcmp(ptr, "-o", 2) == 0) {
            os = 1;
        } else if (memcmp(ptr, "-c", 2) == 0) {
            ca = 1;
        } else if (memcmp(ptr, "-s", 2) == 0) {
            signer = 1;
        } else if (memcmp(ptr, "-f", 2) == 0) {
            sfs = 1;
        } else {
            rc = IOS_ERROR_INVALID;
            goto incVersion_out;
        }
    }

    if (os) {
        rc = EE_IncOsVersion();
        if (rc < 0) {
            goto incVersion_out;
        }
        printf("Incremented OS version\n");
    }

    if (ca) {
        rc = EE_IncCaCrlVersion();
        if (rc < 0) {
            goto incVersion_out;
        }
        printf("Incremented CA CRL version\n");
    }

    if (signer) {
        rc = EE_IncSignerCrlVersion();
        if (rc < 0) {
            goto incVersion_out;
        }
        printf("Incremented Signer CRL version\n");
    }

    if (sfs) {
        rc = EE_IncSfsVersion();
        if (rc < 0) {
            goto incVersion_out;
        }
        printf("Incremented SFS version\n");
    }

incVersion_out:

    if (rc != IOS_ERROR_OK) {
        printf("incVersion failed, rc=%d\n", rc);
    }

    return (rc);

}  /* incVersion */


static IOSError
clearBoot2Version(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 i, addr, value, count;

    /* Boot2 versioning info: half-word 36-45 */
    addr  = 36;
    value = 0;
    count = 10; 

    for (i = 0; i < count; i++) {
        /* Enable write */
        rc = EE_WenCmd();
        if (rc != IOS_ERROR_OK) {
            goto clearBoot2Version_out;
        }

        /* Write to EEPROM */
        rc = EE_WrCmd(addr+i, value);
        if (rc != IOS_ERROR_OK) {
            goto clearBoot2Version_out;
        }

        /* Disable write */
        rc = EE_WdsCmd();
        if (rc != IOS_ERROR_OK) {
            goto clearBoot2Version_out;
        }

        printf("EEPROM[%3d] <= 0\n", addr+i);
    }

clearBoot2Version_out:

    if (rc != IOS_ERROR_OK) {
        printf("clearBoot2Version failed, rc=%d\n", rc);
    }

    return (rc);

}  /* clearBoot2Version */


#define EEPROM_BWD_SS_OFS       66

static IOSError
writeSS(char *args, char *d)
{
    IOSError rc = IOS_ERROR_OK;
    u32 val1, val2;
    char *ptr;

    /* Get value */
    if (getNextToken(&ptr, &args) == 0) {
        printf("Usage: writeSS value\n");
        goto writeSS_out;
    }
    val1 = asciiToInt(ptr);
    val1 &= 0xffff;

    /* Enable write */
    rc = EE_WenCmd();
    if (rc != IOS_ERROR_OK) {
        goto writeSS_out;
    }

    /* Write to EEPROM */
    rc = EE_WrCmd(EEPROM_BWD_SS_OFS, val1);
    if (rc != IOS_ERROR_OK) {
        goto writeSS_out;
    }

    /* Disable write */
    rc = EE_WdsCmd();
    if (rc != IOS_ERROR_OK) {
        goto writeSS_out;
    }

    rc = EE_RdCmd(EEPROM_BWD_SS_OFS, &val2);
    if (rc != IOS_ERROR_OK) {
        goto writeSS_out;
    }
    val2 &= 0xffff;

    printf("Wrote 0x%x to location %d\n", val2, EEPROM_BWD_SS_OFS );

writeSS_out:

    if (rc != IOS_ERROR_OK) {
        printf("writeSS failed, rc=%d\n", rc);
    }

    return (rc);

}  /* writeSS */


void
main(void)
{
    char line[LINE_SIZE];

    printf("eemon [");
    printf("built: " BUILD_TIME "]\n\n");
    initChip();
    initSWWorkArounds(0,0);

    /* Initialize the GPIO setup */
    EE_GPIOSetup();

    while (1) {
        printf("Enter command: ");
        gets(line);
        if (parseCommand(line, commands) < 0) {
            help(line, (void *)commands);
        }
    }
}
