1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//! Configuration of the installed systemd-boot environment.

use std::{fs, path::Path, str::FromStr};

use crate::{Entry, generate_builder_method, LibSDBootConfError};

/// An abstraction over the configuration file of systemd-boot.
#[derive(Default, Debug)]
pub struct Config {
    /// Pattern to select the default entry in the list of entries.
    pub default: Option<String>,
    /// Timeout in seconds for how long to show the menu.
    pub timeout: Option<u32>,
}

impl FromStr for Config {
    type Err = LibSDBootConfError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut config = Self::default();
        let lines = s.lines();

        for line in lines {
            if line.starts_with('#') {
                continue;
            }

            let mut parts = line.splitn(2, ' ');
            let key = parts.next().ok_or(LibSDBootConfError::ConfigParseError)?;
            let value = parts.next().ok_or(LibSDBootConfError::ConfigParseError)?;

            match key {
                "default" => config.default = Some(value.to_string()),
                "timeout" => config.timeout = Some(value.parse().unwrap_or_default()),
                _ => continue,
            }
        }

        Ok(config)
    }
}

impl ToString for Config {
    fn to_string(&self) -> String {
        let mut buffer = String::new();

        if let Some(default) = &self.default {
            buffer.push_str(&format!("default {}\n", default));
        }

        if let Some(timeout) = &self.timeout {
            buffer.push_str(&format!("timeout {}\n", timeout));
        }

        buffer
    }
}

impl Config {
    /// Create a new `Config`.
    ///
    /// # Examples
    ///
    /// ```
    /// use libsdbootconf::config::Config;
    ///
    /// let config = Config::new(Some("5.12.0-aosc-main"), Some(5));
    ///
    /// assert_eq!(config.default, Some("5.12.0-aosc-main".to_owned()));
    /// assert_eq!(config.timeout, Some(5));
    /// ```
    pub fn new<S: Into<String>>(default: Option<S>, timeout: Option<u32>) -> Config {
        Config {
            default: default.map(|x| x.into()),
            timeout,
        }
    }

    /// Load an existing config file.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use libsdbootconf::config::Config;
    ///
    /// let config = Config::load("/path/to/config").unwrap();
    /// ```
    pub fn load<P: AsRef<Path>>(path: P) -> Result<Config, LibSDBootConfError> {
        Config::from_str(&fs::read_to_string(path.as_ref())?)
    }

    /// Save the config to a file.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use libsdbootconf::config::Config;
    ///
    /// let config = Config::new(Some("5.12.0-aosc-main"), Some(5));
    /// config.write("/path/to/config").unwrap();
    /// ```
    pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<(), LibSDBootConfError> {
        fs::write(path.as_ref(), self.to_string())?;

        Ok(())
    }

    /// Set an Entry as the default boot entry.
    ///
    /// # Examples
    ///
    /// ```
    /// use libsdbootconf::{Entry, Config};
    ///
    /// let mut config = Config::default();
    /// let entry = Entry::new("5.12.0-aosc-main", Vec::new());
    ///
    /// config.set_default(&entry);
    ///
    /// assert_eq!(config.default, Some("5.12.0-aosc-main".to_owned()));
    /// ```
    pub fn set_default(&mut self, default: &Entry) {
        self.default = Some(default.id.to_owned());
    }
}

/// Builder for `Config`.
#[derive(Default, Debug)]
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    /// Create an empty `ConfigBuilder`.
    pub fn new() -> Self {
        Self {
            config: Config::default(),
        }
    }

    generate_builder_method!(
        /// Set the default entry with a `String`.
        option REAL(config) default(S => String)
    );
    generate_builder_method!(
        /// Set the timeout.
        option REAL(config) timeout(U => u32)
    );

    /// Set the default entry with an `Entry`.
    pub fn default_entry(mut self, entry: &Entry) -> Self {
        self.config.set_default(entry);

        self
    }

    /// Build the `Config`.
    pub fn build(self) -> Config {
        self.config
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builder() {
        let entry = ConfigBuilder::new().default("5.12.0-aosc-main").build();

        println!("{:?}", &entry);
    }
}