use ext2::{
    fs::{
        sync::{Inode, Synced},
        Ext2,
    },
    sector::{SectorSize, Size1024},
    volume::Volume,
};
use spin::Lazy;

pub static FILE_SYSTEM: Lazy<spin::Mutex<Synced<Ext2<Size1024, Vec<u8>>>>> =
    Lazy::new(|| spin::Mutex::new(load_fs()));

pub fn walk<S: SectorSize, V: Volume<u8, S>>(
    fs: &Synced<Ext2<S, V>>,
    inode: Inode<S, V>,
    name: String,
) {
    if let Some(dir) = inode.directory() {
        for entry in dir {
            assert!(entry.is_ok());
            let entry = entry.unwrap();
            let entry_name = String::from_utf8_lossy(&entry.name);

            println!("{}/{} => {}", name, entry_name, entry.inode,);
            if entry_name != "." && entry_name != ".." {
                walk(
                    fs,
                    fs.inode_nth(entry.inode).unwrap(),
                    format!("{}/{}", name, entry_name),
                );
            }
        }
    }
}

fn load_fs() -> Synced<Ext2<Size1024, Vec<u8>>> {
    let mut volume = Vec::new();
    volume.extend_from_slice(include_bytes!("../../../userland/root_fs/ext2.img"));

    Synced::<Ext2<Size1024, _>>::new(volume).unwrap()
}
