A tmpfiles.d implementation for UNIX-like operating systems.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use crate::parser::{self, Config};

use std::{fs::DirBuilder, os::unix::fs::DirBuilderExt};

pub fn create() -> Result<(), std::io::Error> {
    let mut configs = Vec::new();
    if let config_files = std::fs::read_dir("/usr/lib/tmpfiles.d").unwrap() {
        for file in config_files {
            match file {
                Ok(f) => match parser::parse(&f.path()) {
                    Ok(config) => configs.push(config),
                    Err(e) => return Err(e),
                },
                Err(e) => return Err(e),
            }
        }
    }

    let mut builder = DirBuilder::new();
    for config in &configs {
        for line in config {
            // println!("{:#?}", config);
            if &line.file_type == "d" {
                // println!("{:#?}", line);
                match builder
                    .recursive(true)
                    .mode(line.mode.parse::<u32>().unwrap())
                    .create(&line.path.as_os_str())
                {
                    Ok(k) => println!("Created path: {:#?}", &line.path.as_os_str()),
                    Err(e) => {
                        println!("Failed");
                        return Err(e)
                    },
                }
            }
        }
    }
    Ok(())
}