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

use serde::Deserialize;

use crate::error::Error;

#[derive(Debug, Deserialize)]
pub struct Config {
    pub search_paths: Vec<PathBuf>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            search_paths: vec!["/lib".into(), "/usr/lib".into()],
        }
    }
}

impl Config {
    const DEFAULT_PATH: &str = "/etc/dyn-loader.toml";

    pub fn load_or_default() -> Result<Config, Error> {
        let default_path: &Path = Self::DEFAULT_PATH.as_ref();
        if !default_path.exists() {
            return Ok(Config::default());
        }
        let config = fs::read_to_string(default_path)?;
        toml::from_str(&config).map_err(Error::ConfigError)
    }

    pub fn extend_from_env(&mut self) {
        if let Ok(library_path) = env::var("LD_LIBRARY_PATH") {
            for path in library_path
                .split([':', ';'])
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                self.search_paths.insert(0, path.into());
            }
        }
    }
}
