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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#![warn(clippy::pedantic)]

use chrono::prelude::*;
use log::{info, trace};
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Display, Formatter};
use std::fs::File;
use std::io::{BufRead, BufReader, Error};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use sysinfo::ProcessExt;
use sysinfo::SystemExt;

const SWYT_DIRECTORY_NAME: &str = "swyt";
const CONFIG_FILE_NAME: &str = "config.jbb";
const RULES_FILE_NAME: &str = "rules.jbb";

const DEFAULT_CHECK_INTERVAL: u32 = 60;

type Rules = HashMap<String, Vec<Period>>;

pub struct Rule {
    process_name: String,
    allowed_periods: Vec<Period>,
}

#[derive(Debug, Clone)]
pub struct Period {
    days_of_week: HashSet<Weekday>,
    begin_time: NaiveTime,
    end_time: NaiveTime,
}

pub struct Configuration {
    check_interval: u32,
}

impl Configuration {
    #[must_use]
    pub fn check_interval(&self) -> u32 {
        self.check_interval
    }
}

impl Default for Configuration {
    fn default() -> Self {
        Configuration {
            check_interval: DEFAULT_CHECK_INTERVAL,
        }
    }
}

#[derive(Debug)]
pub enum SwytError {
    ConfigFileNotFound,
    ConfigParseError,
    RuleParseError,
    ProcessFetchError,
    ProcessKillError,
    IoError(std::io::Error),
}

impl Display for SwytError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match *self {
            SwytError::ConfigFileNotFound => write!(f, "Couldn't find config file"),
            SwytError::ConfigParseError => write!(f, "Couldn't parse config file"),
            SwytError::RuleParseError => write!(f, "Couldn't parse rule"),
            SwytError::ProcessFetchError => write!(f, "Couldn't fetch process"),
            SwytError::ProcessKillError => write!(f, "Couldn't kill process"),
            SwytError::IoError(ref err) => std::fmt::Display::fmt(err, f),
        }
    }
}

impl From<std::io::Error> for SwytError {
    fn from(io_error: Error) -> Self {
        SwytError::IoError(io_error)
    }
}

pub fn process_rules(rules: &Rules) {
    trace!("Process rules...");
    let current_date_time = Local::now();
    let mut sys = sysinfo::System::new_all();
    sys.refresh_processes();
    let processes = sys.processes().values();
    for process in processes {
        let process_name = process.name();
        if let Some(periods) = rules.get(process_name) {
            if !periods.iter().any(|p| {
                p.days_of_week
                    .contains(&current_date_time.date_naive().weekday())
                    && current_date_time.time() >= p.begin_time
                    && current_date_time.time() <= p.end_time
            }) {
                trace!("Killed process {}", process_name);
                process.kill();
            }
        }
    }
}

/// # Errors
/// This will return an error if the rules file can't be parsed
pub fn load_rules(swyt_filepath: &Path) -> Result<Rules, SwytError> {
    let rules_filepath = get_rules_filepath(swyt_filepath);
    parse_rules_file(&rules_filepath)
}

/// # Errors
/// This will return an error if the config file can't be parsed
pub fn load_config(swyt_filepath: &Path) -> Result<Configuration, SwytError> {
    let config_filepath = get_config_filepath(swyt_filepath);
    parse_config_file(&config_filepath)
}

fn get_config_filepath(swyt_filepath: &Path) -> PathBuf {
    let mut config_directory = swyt_filepath.to_path_buf();
    config_directory.push(CONFIG_FILE_NAME);
    config_directory
}

fn get_rules_filepath(swyt_filepath: &Path) -> PathBuf {
    let mut rules_filepath = swyt_filepath.to_path_buf();
    rules_filepath.push(RULES_FILE_NAME);
    rules_filepath
}

/// # Errors
/// This will return an error if the config file is not found
pub fn find_swyt_filepath() -> Result<PathBuf, SwytError> {
    let mut config_directory = dirs::config_dir().ok_or(SwytError::ConfigFileNotFound)?;
    config_directory.push(SWYT_DIRECTORY_NAME);
    Ok(config_directory)
}

fn parse_rules_file(rules_filepath: &PathBuf) -> Result<Rules, SwytError> {
    if !rules_filepath.exists() {
        info!("Rules file doesn't exist, no rule will be executed.");
        return Ok(Rules::new());
    }

    let mut rules = Rules::new();
    let rules_file = File::open(rules_filepath)?;
    let reader = BufReader::new(rules_file);
    for line in reader.lines() {
        let rule = parse_rule(&line?)?;
        info!("Rule found for process: {}", rule.process_name);
        rules.insert(rule.process_name, rule.allowed_periods);
    }

    Ok(rules)
}

fn parse_rule(rule: &str) -> Result<Rule, SwytError> {
    let mut split_rule = rule.split('=');
    let process_name = split_rule
        .next()
        .ok_or(SwytError::RuleParseError)?
        .to_string();
    let periods_string = split_rule.next().ok_or(SwytError::RuleParseError)?;

    let allowed_periods: Vec<Period> = periods_string
        .split('|')
        .map(parse_periods)
        .collect::<Result<Vec<Vec<Period>>, SwytError>>()?
        .iter()
        .flatten()
        .cloned()
        .collect();
    Ok(Rule {
        process_name,
        allowed_periods,
    })
}

fn parse_periods(period: &str) -> Result<Vec<Period>, SwytError> {
    let mut split_period = period.split(';');
    let period_time = split_period.next().ok_or(SwytError::RuleParseError)?;
    let period_days_of_week = split_period.next().ok_or(SwytError::RuleParseError)?;
    let start_ends = parse_period_times(period_time)?;
    let days_of_week = parse_days_of_week(period_days_of_week)?;

    Ok(start_ends
        .iter()
        .map(|&(begin_time, end_time)| Period {
            days_of_week: days_of_week.clone(),
            begin_time,
            end_time,
        })
        .collect())
}

fn parse_period_times(period_times: &str) -> Result<Vec<(NaiveTime, NaiveTime)>, SwytError> {
    period_times
        .split(',')
        .map(parse_period_time)
        .collect::<Result<_, SwytError>>()
}

fn parse_period_time(period_time: &str) -> Result<(NaiveTime, NaiveTime), SwytError> {
    if let "*" = period_time {
        Ok((
            NaiveTime::from_hms_opt(0, 0, 0).ok_or(SwytError::RuleParseError)?,
            NaiveTime::from_hms_opt(23, 59, 59).ok_or(SwytError::RuleParseError)?,
        ))
    } else {
        let mut split_time = period_time.split('~');
        let begin_time = parse_time(split_time.next().ok_or(SwytError::RuleParseError)?)?;
        let end_time = parse_time(split_time.next().ok_or(SwytError::RuleParseError)?)?;
        Ok((begin_time, end_time))
    }
}

fn parse_time(time: &str) -> Result<NaiveTime, SwytError> {
    let mut split_time = time.split(':');
    let hours = u32::from_str(split_time.next().ok_or(SwytError::RuleParseError)?)
        .map_err(|_| SwytError::RuleParseError)?;
    let minutes = u32::from_str(split_time.next().ok_or(SwytError::RuleParseError)?)
        .map_err(|_| SwytError::RuleParseError)?;

    NaiveTime::from_hms_opt(hours, minutes, 0).ok_or(SwytError::RuleParseError)
}

fn parse_days_of_week(days_of_week: &str) -> Result<HashSet<Weekday>, SwytError> {
    days_of_week
        .split(',')
        .map(parse_day_of_week)
        .collect::<Result<HashSet<Weekday>, SwytError>>()
}

fn parse_day_of_week(day_of_week: &str) -> Result<Weekday, SwytError> {
    Ok(match day_of_week {
        "MO" => Weekday::Mon,
        "TU" => Weekday::Tue,
        "WE" => Weekday::Wed,
        "TH" => Weekday::Thu,
        "FR" => Weekday::Fri,
        "SA" => Weekday::Sat,
        "SU" => Weekday::Sun,
        _ => return Err(SwytError::RuleParseError),
    })
}

fn parse_config_file(config_filepath: &PathBuf) -> Result<Configuration, SwytError> {
    if !config_filepath.exists() {
        info!("Configuration file doesn't exist, using defaults");
        return Ok(Configuration::default());
    }

    let mut config = Configuration::default();
    let config_file = File::open(config_filepath)?;
    let reader = BufReader::new(config_file);
    for line in reader.lines() {
        parse_config_line(&line?, &mut config)?;
    }

    Ok(config)
}

fn parse_config_line(line: &str, config: &mut Configuration) -> Result<(), SwytError> {
    let mut split_line = line.split('=');
    let config_identifier = split_line.next().ok_or(SwytError::ConfigParseError)?.trim();
    let config_value = split_line.next().ok_or(SwytError::ConfigParseError)?.trim();

    if let "check_interval" = config_identifier {
        let value = u32::from_str(config_value).unwrap_or(DEFAULT_CHECK_INTERVAL);
        config.check_interval = value;
    }

    Ok(())
}

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

    const VALID_CONFIG_SWYT_PATH: &str = "./test_data/valid_config";
    const MISSING_VALUE_CONFIG_SWYT_PATH: &str = "./test_data/missing_value_config";
    const INVALID_CONFIG_SWYT_PATH: &str = "./test_data/invalid_config";
    const VALID_RULES_SWYT_PATH: &str = "./test_data/valid_rules";
    const NO_RULE_SWYT_PATH: &str = "./test_data/no_rule";
    const INVALID_RULES_SWYT_PATH: &str = "./test_data/invalid_rules";

    #[test]
    pub fn load_config_valid() {
        let config = load_config(Path::new(VALID_CONFIG_SWYT_PATH)).unwrap();
        assert_eq!(config.check_interval(), 120);
    }

    #[test]
    pub fn load_config_missing_value() {
        let config = load_config(Path::new(MISSING_VALUE_CONFIG_SWYT_PATH)).unwrap();
        assert_eq!(config.check_interval(), 60);
    }

    #[test]
    pub fn load_config_bad_value() {
        let config = load_config(Path::new(INVALID_CONFIG_SWYT_PATH)).unwrap();
        assert_eq!(config.check_interval(), 60);
    }

    #[test]
    pub fn load_rules_valid() {
        let rules = load_rules(Path::new(VALID_RULES_SWYT_PATH)).unwrap();

        assert_eq!(rules.len(), 3);

        let process0_rules = rules.get("process0").unwrap();
        let process0_first_rule = process0_rules.get(0).unwrap();
        assert_eq!(
            process0_first_rule.begin_time,
            NaiveTime::from_hms_opt(18, 00, 00).unwrap()
        );
        assert_eq!(
            process0_first_rule.end_time,
            NaiveTime::from_hms_opt(20, 00, 00).unwrap()
        );
        assert!(process0_first_rule.days_of_week.contains(&Weekday::Mon));
        assert!(process0_first_rule.days_of_week.contains(&Weekday::Tue));
        assert!(process0_first_rule.days_of_week.contains(&Weekday::Wed));

        let process0_second_rule = process0_rules.get(1).unwrap();
        assert_eq!(
            process0_second_rule.begin_time,
            NaiveTime::from_hms_opt(12, 00, 00).unwrap()
        );
        assert_eq!(
            process0_second_rule.end_time,
            NaiveTime::from_hms_opt(14, 00, 00).unwrap()
        );
        assert!(process0_second_rule.days_of_week.contains(&Weekday::Thu));
        assert!(process0_second_rule.days_of_week.contains(&Weekday::Fri));

        let process0_third_rule = process0_rules.get(2).unwrap();
        assert_eq!(
            process0_third_rule.begin_time,
            NaiveTime::from_hms_opt(00, 00, 00).unwrap()
        );
        assert_eq!(
            process0_third_rule.end_time,
            NaiveTime::from_hms_opt(23, 59, 59).unwrap()
        );
        assert!(process0_third_rule.days_of_week.contains(&Weekday::Sat));
        assert!(process0_third_rule.days_of_week.contains(&Weekday::Sun));

        let process1_rules = rules.get("process1").unwrap();
        let process1_first_rule = process1_rules.get(0).unwrap();
        assert_eq!(
            process1_first_rule.begin_time,
            NaiveTime::from_hms_opt(10, 00, 00).unwrap()
        );
        assert_eq!(
            process1_first_rule.end_time,
            NaiveTime::from_hms_opt(11, 00, 00).unwrap()
        );
        assert!(process1_first_rule.days_of_week.contains(&Weekday::Mon));
        assert!(process1_first_rule.days_of_week.contains(&Weekday::Tue));
        assert!(process1_first_rule.days_of_week.contains(&Weekday::Wed));

        let process2_rules = rules.get("process2").unwrap();
        let process2_first_rule = process2_rules.get(0).unwrap();
        assert_eq!(
            process2_first_rule.begin_time,
            NaiveTime::from_hms_opt(12, 00, 00).unwrap()
        );
        assert_eq!(
            process2_first_rule.end_time,
            NaiveTime::from_hms_opt(15, 00, 00).unwrap()
        );
        assert!(process2_first_rule.days_of_week.contains(&Weekday::Mon));
        assert!(process2_first_rule.days_of_week.contains(&Weekday::Thu));
        assert!(process2_first_rule.days_of_week.contains(&Weekday::Fri));
    }

    #[test]
    fn load_invalid_rules() {
        assert!(matches!(
            load_rules(Path::new(INVALID_RULES_SWYT_PATH)),
            Err(SwytError::RuleParseError)
        ));
    }

    #[test]
    fn load_no_rule() {
        let rules = load_rules(Path::new(NO_RULE_SWYT_PATH)).unwrap();
        assert_eq!(rules.len(), 0);
    }
}