#!/usr/bin/env python3
import serial
import argparse
import os

#we send syn, recv ack
SYN_MAGIC = 0xdeafbeef 
ACK_MAGIC = 0xf00dd00d

EEPROM_PAGESIZE = 64
EEPROM_FILE = "./compiled_eeprom"


parser = argparse.ArgumentParser(description="sends binary file over serial so the avr can write it to eeprom")
parser.add_argument('port', type=str)
parser.add_argument('baud', type=int)
args = parser.parse_args()

eeprom_file = open("./compiled_eeprom", "rb")
eeprom_filesize = os.fstat(eeprom_file.fileno()).st_size

s = serial.Serial(args.port, args.baud, timeout = 0)
s.write(SYN_MAGIC)

def handle_writer_error():
    if write_status == 1: # verification failed
        print("Verification failed on page {}!".format(page))
    elif write_status == 0xff:
        print("Unknown error writing page {}!".format(page))


while not s.read(4) == ACK_MAGIC:
    pass

print("Device detected, writing eeprom...")
for page in range(0, int(eeprom_filesize / EEPROM_PAGESIZE)):
    s.write(eeprom_file.read(EEPROM_PAGESIZE))
    write_status = s.read(1)
    if not write_status == 0:
        handle_writer_error(write_status)

if eeprom_file.tell() < eeprom_filesize:
    s.write(eeprom_file.read())
    [s.write(0) for b in range(0, eeprom_filesize % EEPROM_PAGESIZE)]
    write_status = s.read(1)
    if not write_status == 0:
        handle_writer_error(write_status)


print("Done writing to EEPROM! You are still alone!")
