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
use anyhow::{anyhow, Result};
use confy;
use dialoguer::{Confirm, Input};
use directories::UserDirs;
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::path::PathBuf;
use which::which;

const DEFAULT_REMOTE: &str = "origin";
const CONFIG_FILE: &str = ".mob";

pub const VAR_NEXT_DRIVER: &str = "NEXT_DRIVER";
pub const VAR_CURRENT_DRIVER: &str = "CURRENT_DRIVER";

const AFTER_TIMER_MESSAGE: &str = "mob next NEXT_DRIVER";

#[derive(Serialize, Deserialize)]
pub struct Hooks {
    pub before_start: Option<String>,
    pub after_start: Option<String>,
    pub after_timer: Option<String>,
    pub before_next: Option<String>,
    pub after_next: Option<String>,
    pub before_done: Option<String>,
    pub after_done: Option<String>,
}

impl Hooks {
    pub fn new(after_timer: Option<String>) -> Self {
        Hooks {
            before_start: None,
            after_start: None,
            after_timer,
            before_next: None,
            after_next: None,
            before_done: None,
            after_done: None,
        }
    }
}

#[derive(Serialize, Deserialize)]
pub struct Config {
    pub name: String,
    pub remote: String,
    pub hooks: Hooks,
}

impl Config {
    pub fn ask() -> Result<Config> {
        log::info!("It seems like this is the first time you run mob. Welcome!");

        let name = Input::new()
            .with_prompt("Your name")
            .default(whoami::realname())
            .interact()?;

        let remote = Input::new()
            .with_prompt("Remote name you will use")
            .default(DEFAULT_REMOTE.to_string())
            .interact()?;

        let after_timer = ask_after_timer();
        let hooks = Hooks::new(after_timer);

        Ok(Config {
            name,
            remote,
            hooks,
        })
    }
}

fn ask_after_timer() -> Option<String> {
    let cmd = match after_timer_command() {
        Some(cmd) => cmd,
        None => return None,
    };

    log::info!("Command to run when your turn is done:");
    log::info!("  {}", &cmd);

    Confirm::new()
        .with_prompt("Add this to your config?")
        .default(true)
        .interact()
        .unwrap()
        .then(|| cmd)
}

fn after_timer_command() -> Option<String> {
    let cmd = [get_sound_command(), get_notify_command()]
        .iter()
        .filter_map(|c| c.clone())
        .collect::<Vec<String>>()
        .join(";");

    if cmd.is_empty() {
        return None;
    }
    Some(cmd)
}

fn get_sound_command() -> Option<String> {
    which("say")
        .map(format_cmd)
        .or_else(|_| {
            which("festival").map(|p| {
                format!(
                    "echo '{}' | {} --tts",
                    AFTER_TIMER_MESSAGE,
                    p.to_str().unwrap()
                )
            })
        })
        .or_else(|_| which("spd-say").map(format_cmd))
        .or_else(|_| which("espeak").map(format_cmd))
        .or_else(|_| which("beep").map(|p| p.into_os_string().into_string().unwrap()))
        .ok()
}

fn get_notify_command() -> Option<String> {
    which("osascript")
        .map(|p| {
            format!(
                r#"{} -e 'display notification "{}"'"#,
                p.to_str().unwrap(),
                AFTER_TIMER_MESSAGE
            )
        })
        .or_else(|_| which("notify-send").map(format_cmd))
        .ok()
}

fn format_cmd(path: PathBuf) -> String {
    format!("{} '{}'", path.to_str().unwrap(), AFTER_TIMER_MESSAGE)
}

impl Default for Config {
    fn default() -> Self {
        Self {
            name: "".to_string(),
            remote: DEFAULT_REMOTE.to_string(),
            hooks: Hooks::new(None),
        }
    }
}

pub fn load() -> Result<Config> {
    let path = {
        let user_dirs = UserDirs::new().unwrap();
        let home_dir = user_dirs.home_dir();
        home_dir.join(CONFIG_FILE)
    };
    let path_str = path.to_str().unwrap();

    let config: Config = confy::load_path(&path).map_err(|e| {
        anyhow!(
            "Failed to load config, check '{}' (or delete it to recreate): {}",
            &path_str,
            e
        )
    })?;

    if config.name.is_empty() {
        let config = Config::ask()?;
        confy::store_path(&path, &config)?;
        log::info!("Stored config to {}", &path_str);
        return Ok(config);
    }
    Ok(config)
}