#!/usr/bin/env python3

import time
import shutil
from pathlib import Path
from argparse import ArgumentParser
from mmap import mmap, ACCESS_READ


def get_args():
    parser = ArgumentParser()
    parser.add_argument("firmware", help="firmware to parse version", type=Path, nargs="+")
    return parser.parse_args()


def get_version(firmware: Path) -> list[str,str]:
    pattern = b"MicroPython v"
    with firmware.open("rb") as fd:
        with mmap(fd.fileno(), 0, access=ACCESS_READ) as mm:
            idx = mm.find(pattern) + len(pattern) - 1
            end = mm.find(b"\0", idx)
            version,_ , compile_date = mm[idx:end].decode().split()

    version = "-".join(version.split("-")[:-1])
    return version, compile_date


def main():
    # args = get_args()
    firmwares = [board for board in Path("/home/esp32/micropython/ports/esp32").glob("build-*/firmware.bin")]

    for old_firmware in Path("/home/public/www/micropython/esp32").glob("*.bin"):
        old_firmware.unlink()

    for firmware in firmwares:
        version, compile_date = get_version(firmware)
        target = Path("/home/public/www/micropython/esp32").joinpath(f"{firmware.parent.name.removeprefix('build-')}-{version}-{compile_date}.bin")
        shutil.copy(firmware, target)
        print(target)


if __name__ == "__main__":
    main()
