
// uC includes
#include "../common/io.c"
#include "../common/lib.c"

typedef unsigned char u8;
typedef unsigned short u16;

const char * HEX_LUT = "0123456789ABCDEF";

int main () {
    u8 *buf = (mem + 0x2400); // >=> 0x2400
    u8 sha_buf[0x20];         // >=> sp

    puts("Welcome to the test program loader.");

    puts ("Enabling hardened mode");
    INT (0x40);

    puts ("Verifying 0x7f interrupt disabled");
    INT (0x7f);

    puts ("0x7f interrupt disabled, key stored in internal SRAM");
    puts ("unlock by providing the 16 byte key to 0x41 interrupt");

    memset (&sha_buf, 0, 0x20);
    puts ("Internal SRAM Hash:");
    // address, size, out_buf
    sha256_internal (0, 0x1000, (char*) &sha_buf);

addr_44aa:
    for (int i /* r11 */ = 0; i != 0x20; i++) {
        u8 upper_nibble /* r14 */ = sha_buf[i];
        char lower_char /* r11 */ = HEX_LUT[upper_nibble & 0xf];
        upper_nibble /* r14 */    = (upper_nibble >> 0x4) & 0xf;
        putchar (HEX_LUT[upper_nibble]);
        putchar (lower_char);
    }
    puts (""); // prints newline

    while (1) {
        u16 loadaddr /* r11 */;
        u8 len /* r10 */;
        puts ("Please enter debug payload.");

        memset (buf, 0, 0x400);
        getsn (buf, 0x3ff);

        loadaddr = (buf[0] << 8) + (buf[1]);
        len      = buf[3];

        // the program no longer checks the load address location or alignment
        if (len - 6 > 0x3bb) {
            puts ("Invalid payload length");
            continue;
        }

        puts ("Executing debug payload");
        memcpy (mem + loadaddr, buf + 0x4, len);

        // todo: *loadaddr ();

    }
}
