// build.rs

use std::env;
use std::path::PathBuf;

fn main() {
    let cube_path = PathBuf::from("/home/priec/programs/STM32CubeU5");

    let hal_driver = cube_path.join("Drivers/STM32U5xx_HAL_Driver");
    let cmsis = cube_path.join("Drivers/CMSIS");
    let device = cmsis.join("Device/ST/STM32U5xx");
    let example_inc = cube_path.join("Projects/NUCLEO-U575ZI-Q/Examples/GPIO/GPIO_IOToggle/Inc");

    // HAL source files
    let hal_srcs = [
        "stm32u5xx_hal.c",
        "stm32u5xx_hal_rcc.c",
        "stm32u5xx_hal_rcc_ex.c",
        "stm32u5xx_hal_pwr.c",
        "stm32u5xx_hal_pwr_ex.c",
        "stm32u5xx_hal_gpio.c",
        "stm32u5xx_hal_cortex.c",
        "stm32u5xx_hal_flash.c",
        "stm32u5xx_hal_flash_ex.c",
        "stm32u5xx_hal_icache.c",
        "stm32u5xx_hal_ramcfg.c",
        "stm32u5xx_hal_rtc.c",
        "stm32u5xx_hal_rtc_ex.c",
        "stm32u5xx_hal_iwdg.c",
    ];

    let mut build = cc::Build::new();

    // system_stm32u5xx.c adds SystemCoreClock, tables, etc.
    build.file(device.join("Source/Templates/system_stm32u5xx.c"));
    for src in hal_srcs {
        build.file(hal_driver.join("Src").join(src));
    }

    build
        .include(hal_driver.join("Inc"))
        .include(device.join("Include"))
        .include(cmsis.join("Core/Include"))
        .include(&example_inc)
        .define("USE_HAL_DRIVER", None)
        .define("STM32U575xx", None)
        .define("HAL_IWDG_MODULE_ENABLED", None)
        .flag("-mthumb")
        .flag("-march=armv8-m.main+fp.dp")
        .flag("-mfloat-abi=hard")
        .warnings(false)
        .compile("stm32u5_hal");

    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed={}", hal_driver.display());
    println!("cargo:rerun-if-changed={}", example_inc.display());
}
