import os

base_address = 0x80400000  # 第一个应用的起始地址
step = 0x20000  # 每个应用的大小
linker = "src/linker.ld"  # 自定义链接脚本

RUST_FLAGS = f"-Clink-arg=-T{linker} "  # 使用我们自己的链接脚本
RUST_FLAGS += "-Cforce-frame-pointers=yes "  # 强制编译器生成帧指针
TARGET = "riscv64gc-unknown-none-elf"

app_id = 0
apps: list[str] = os.listdir("src/bin")
apps.sort()
for app_file in apps:
    app_name = app_file.split(".")[0]

    lines = []  # 修改了base_address linker.ld
    lines_before = []  # 最原本的linker.ld的文本, 最下面会恢复

    # 读出原本文件
    with open(linker, "r") as f:
        for line in f.readlines():
            lines_before.append(line)  # 保存原本的文本
            line = line.replace(hex(base_address), hex(base_address+step*app_id))  # 替换的文本
            lines.append(line)
    with open(linker, "w+") as f:
        f.writelines(lines)

    # 逐个编译
    cmd = f"CARGO_BUILD_RUSTFLAGS='{RUST_FLAGS}' cargo build --bin {app_name} --release --target={TARGET}"
    print(cmd)
    os.system(cmd)

    print(f"[build.py] application {app_name} start with address {hex(base_address+step*app_id)}")

    # 恢复
    with open(linker, "w+") as f:
        f.writelines(lines_before)
    app_id += 1