summaryrefslogtreecommitdiff
path: root/angelsharkd/src/config.rs
blob: d7d18d2a215f38e0509dab66212962ab15285438 (plain) (blame)
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
use anyhow::{Context, Result};
use libangelshark::{Acm, AcmRunner};
use std::{
    env,
    fs::File,
    net::{Ipv4Addr, SocketAddrV4},
};

#[derive(Clone)]
pub struct Config {
    pub bind_addr: SocketAddrV4,
    pub debug_mode: bool,
    pub runner: AcmRunner,
    pub origin: String,
}

impl Config {
    pub fn init() -> Result<Self> {
        let debug_mode = cfg!(debug_assertions) || env::var_os("ANGELSHARKD_DEBUG").is_some();

        let bind_addr: SocketAddrV4 = env::var("ANGELSHARKD_ADDR")
            .map(|addr| addr.parse())
            .unwrap_or_else(|_| Ok(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)))
            .with_context(|| "Failed to parse socket bind address.")?;

        let origin = if debug_mode {
            String::new()
        } else {
            env::var("ANGELSHARKD_ORIGIN").with_context(|| {
                "In release mode, CORS origin cannot be blank. Set ANGELSHARKD_ORIGIN"
            })?
        };

        let logins = if let Ok(path) = env::var("ANGELSHARKD_LOGINS") {
            File::open(path)
        } else {
            File::open("./asa.cfg")
        }
        .with_context(|| "Failed to open logins file.")?;

        let mut runner = AcmRunner::default();
        for (job_name, acm) in
            Acm::from_logins(logins).with_context(|| "Failed to parse logins.")?
        {
            runner.register_acm(&job_name, acm);
        }

        Ok(Self {
            bind_addr,
            origin,
            debug_mode,
            runner,
        })
    }
}