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::fields::sanity_check;

use std::{
    fs::File,
    io::{BufRead, BufReader},
};

#[derive(Debug)]
pub struct Config {
    pub file_type: String,
    pub path: std::path::PathBuf,
    pub mode: String,
    pub user: String,
    pub group: String,
    pub age: String,
    pub argument: String,
}

pub fn parse(config_path: &std::path::Path) -> Result<Vec<Config>, std::io::Error> {
    let mut return_config = Vec::new();

    let tmpfiles_config = read_config(config_path);
    match tmpfiles_config {
        Ok(cfg) => {
            for line in cfg {
                let line: Vec<&str> = line.iter().map(|item| item.as_str()).collect();
                if line[0].chars().next().unwrap().to_string() == "#" {
                    continue;
                }
                return_config.push(Config {
                    file_type: String::from(line[0]),
                    path: line[1].into(),
                    mode: String::from(line[2]),
                    user: String::from(line[3]),
                    group: String::from(line[4]),
                    age: String::from(line[5]),
                    argument: String::from(line[6]),
                });
            }
        }
        Err(e) => {
            return Err(e);
        }
    }
    // for line in return_config {
    //     match sanity_check(line) {
    //         Err(e) => return Err(e)
    //     }
    // }
    Ok(return_config)
}

fn read_config(config_path: &std::path::Path) -> Result<Vec<Vec<String>>, std::io::Error> {
    let mut return_vector = Vec::new();
    let file = File::open(config_path)?;
    for line in BufReader::new(file).lines().map_while(Result::ok) {
        let line: Vec<String> = line
            .split_whitespace()
            .map(|item| item.to_string())
            .collect();
        return_vector.push(line);
    }
    Ok(return_vector)
}