use std::{env, fs, io, path::Path, process::Command};

fn io_err(st: &'static str) -> io::Error
{
   io::Error::new(io::ErrorKind::Other, st)
}

fn traverse_dir(path: &Path) -> io::Result<()>
{
   for ent in fs::read_dir(path)? {
      let path = ent?.path();

      if path.is_dir() {
         traverse_dir(&path)?;
      } else {
         if let Some(path) = path.to_str() {
            println!("cargo:rerun-if-changed={}", path);
         } else {
            return Err(io_err("failed to convert path"));
         }
      }
   }

   Ok(())
}

fn main() -> io::Result<()>
{
   let out_file = env::var("OUT_DIR").unwrap();
   let out_file = format!("--target={}/resources", out_file);

   // traverse each file in the data directory, because cargo won't do this
   traverse_dir(Path::new("data"))?;

   let o = Command::new("glib-compile-resources").arg("data/resources.xml")
                                                 .arg(out_file)
                                                 .output()
                                                 .unwrap();

   if !o.status.success() {
      dbg!(o);
      Err(io_err("failed to compile resources"))
   } else {
      Ok(())
   }
}

// EOF
