use std::fs;

use crate::{env::BuildEnv, error::Error, util};

use super::cargo::CargoBuilder;

pub fn install_ygglibc(env: &BuildEnv) -> Result<(), Error> {
    log::info!("Installing ygglibc into ports sysroot");

    let dst_lib_dir = env.ports_sysroot.join("lib");
    let dst_include_dir = env.ports_sysroot.join("usr/include");
    let ygglibc_dir = env.workspace_root.join("userspace/lib/ygglibc");
    let ygglibc_output_dir = ygglibc_dir
        .join("target")
        .join(format!("{}-unknown-none", env.arch.name()))
        .join(env.profile.name());
    let include_paths = [
        ygglibc_output_dir.join("include"),
        ygglibc_dir.join("include"),
    ];

    fs::create_dir_all(&dst_lib_dir)?;
    fs::create_dir_all(&dst_include_dir)?;

    util::copy_file_if(
        ygglibc_output_dir.join("libygglibc.a"),
        dst_lib_dir.join("libygglibc.a"),
        util::is_newer,
    )?;
    util::copy_file_if(
        ygglibc_output_dir.join("libygglibc.so"),
        dst_lib_dir.join("libygglibc.so"),
        util::is_newer,
    )?;
    util::copy_file_if(
        ygglibc_output_dir.join("crt0.o"),
        dst_lib_dir.join("crt0.o"),
        util::is_newer,
    )?;

    for path in include_paths.iter() {
        util::copy_dir_recursive_if(path, &dst_include_dir, util::is_newer)?;
    }

    Ok(())
}

pub fn build_ygglibc(env: &BuildEnv) -> Result<(), Error> {
    let ygglibc_dir = env.workspace_root.join("userspace/lib/ygglibc");
    CargoBuilder::Ygglibc(env).build(&ygglibc_dir)?;
    Ok(())
}
