use std::{env, fs, path::PathBuf};

use anyhow::Result;
use fs_extra::{copy_items, dir::CopyOptions};

fn main() -> Result<()> {
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
    let source_dir = manifest_dir.join("res");
    let out_dir = PathBuf::from(env::var("OUT_DIR")?);
    let resource_dir = out_dir.join("res");

    let mut copy_options = CopyOptions::new();
    copy_options.overwrite = true;

    println!("cargo:rerun-if-changed={}", source_dir.display());

    if resource_dir.exists() {
        fs::remove_dir_all(&resource_dir)?;
    }

    if source_dir.exists() {
        let items = fs::read_dir(&source_dir)?
            .map(|entry| entry.map(|entry| entry.path()))
            .collect::<Result<Vec<_>, _>>()?;

        fs::create_dir_all(&resource_dir)?;
        copy_items(&items, &resource_dir, &copy_options)?;
    }

    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
        let mut resource = winresource::WindowsResource::new();

        resource.set_icon("res/icon.ico");

        resource.compile().expect("compile windows icon failed");
    }

    println!("cargo:rustc-env=RESOURCE_DIR={}", resource_dir.display());

    Ok(())
}
