summaryrefslogtreecommitdiff
path: root/src/configuration.rs
blob: 5995ffc49e7582c9a74165d38de02ec47c3fc95a (plain)
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
use lexopt::{Parser, prelude::*};

const DEFAULT_ADDRESS: &str = "127.0.0.1:6666";
const DEFAULT_FREQUENCY: u64 = 150;
const DEFAULT_MODULATION: u8 = 5;

#[derive(Clone)]
pub struct Configuration {
    pub address: String,
    pub frequency: u64,
    pub modulation: u8,
}

impl Configuration {
    pub fn new() -> Self {
        let mut address = DEFAULT_ADDRESS.to_string();
        let mut frequency = DEFAULT_FREQUENCY;
        let mut modulation = DEFAULT_MODULATION;

        let mut parser = Parser::from_env();

        while let Ok(Some(argument)) = parser.next() {
            match argument {
                Short('l') | Long("listen-address") => {
                    if let Ok(value) = parser.value().and_then(|v| v.parse()) {
                        address = value;
                    } else {
                        eprintln!("Warning: Invalid listen address ignored.");
                    }
                }
                Short('f') | Long("frequency") => {
                    if let Ok(value) = parser.value().and_then(|v| v.parse()) {
                        frequency = value;
                    } else {
                        eprintln!("Warning: Invalid frequency ignored.");
                    }
                }
                Short('m') | Long("modulation") => {
                    if let Ok(value) = parser.value().and_then(|v| v.parse()) {
                        modulation = value;
                    } else {
                        eprintln!("Warning: Invalid modulation ignored.");
                    }
                }
                Long("help") => {
                    println!(
                        "Usage: tomato-sauce [-l|--listen-address=LISTEN_ADDRESS] [-f|--frequency=NUMBER] [-m|--modulation=NUMBER]"
                    );
                    std::process::exit(0);
                }
                _ => {
                    eprintln!("Warning: Unknown argument ignored");
                }
            }
        }

        Configuration {
            address,
            frequency,
            modulation,
        }
    }
}