use std::path::PathBuf;

fn main() {
    // Only apply bare-metal linker settings when targeting a no_std platform.
    // This allows `cargo publish` verification (which builds for the host) to succeed.
    let target = std::env::var("TARGET").unwrap_or_default();
    if !target.contains("-none") {
        return;
    }

    // The linker script is generated by axhal's build.rs at:
    //   target/<target_triple>/<profile>/linker_<platform>.lds
    
    // Check if axstd feature is enabled (full ArceOS guest/host).
    let axstd_enabled = std::env::var("CARGO_FEATURE_AXSTD").is_ok();
    
    if axstd_enabled {
        let out_dir = std::env::var("OUT_DIR").unwrap();
        let profile_dir = PathBuf::from(&out_dir).join("../../..");
        let profile_dir = std::fs::canonicalize(&profile_dir)
            .unwrap_or_else(|_| PathBuf::from(&out_dir).join("../../.."));

        let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
        let platform = match arch.as_str() {
            "riscv64" => "riscv64-qemu-virt",
            "aarch64" => "aarch64-qemu-virt",
            "x86_64" => "x86-pc",
            "loongarch64" => "loongarch64-qemu-virt",
            other => panic!("Unsupported architecture: {other}"),
        };
        let lds_path = profile_dir.join(format!("linker_{platform}.lds"));

        println!("cargo:rustc-link-arg=-T{}", lds_path.display());
        println!("cargo:rustc-link-arg=-no-pie");
        println!("cargo:rustc-link-arg=-znostart-stop-gc");
    } else {
        // Bare-metal mode (for gkernel on aarch64/x86_64): use our custom linker script.
        let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap();
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
        let linker_script = PathBuf::from(&manifest_dir).join("payload").join("gkernel").join(format!("linker-{arch}.ld"));
        
        if linker_script.exists() {
            println!("cargo:rustc-link-arg=-T{}", linker_script.display());
            println!("cargo:rustc-link-arg=-no-pie");
        } else {
            // riscv64 gkernel might not have a custom linker script here if it expects axstd?
            // But if we are here, axstd is disabled.
            // If riscv64 gkernel NEEDS axstd, we shouldn't be building it without axstd.
            // However, if we accidentally build it without axstd, this might fail or warn.
            // But for aarch64/x86_64 gkernel, it's fine.
             panic!(
                "Missing linker script for bare-metal {arch}: {}",
                linker_script.display()
            );
        }
    }
}
